我通常会尽量避免发布大块凌乱的代码,但如果我将它复制到控制台,我真的无法弄清楚为什么这个脚本可以正常工作,但是如果我将它全部包装在一个函数中然后调用该函数,我得到错误,动画未定义。
var animation;
var e;
var myPath;
var paper = Raphael(document.getElementById('svgArea'), 600, 400);
e = paper.circle(106.117, 82.076, 5, 5).attr({
stroke: "none",
fill: 'red'
});
var path = 'M106.117,82.076c0,0,227.487-121.053,183.042,22.222c-44.445,143.275-95.322,83.041-95.322,83.041L106.117,82.076z';
myPath = paper.path(path).attr({
stroke: 'black',
"stroke-width": 2,
"stroke-opacity": 0.2
});
animation = setInterval("animate()", 10); //execute the animation function all 10ms (change the value for another speed)
var counter = 0; // a counter that counts animation steps
function animate() {
if (myPath.getTotalLength() <= counter) { //break as soon as the total length is reached
counter = 0;
}
var pos = myPath.getPointAtLength(counter); //get the position (see Raphael docs)
e.attr({
cx: pos.x,
cy: pos.y
}); //set the circle position
counter++; // count the step counter one up
};