我通常会尽量避免发布大杂乱的代码块,但我真的无法弄清楚为什么这个脚本工作正常如果我将它复制到控制台,但是如果我将它全部包装在一个函数中然后调用它函数,我得到错误,没有定义动画。
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
};
答案 0 :(得分:2)
@ Coin_op的答案的替代方法是传递函数引用。
animation = setInterval(animate, 10);
答案 1 :(得分:1)
当您将字符串作为字符串传递时,settimeout调用将从动画调用中删除范围。当animate是全局的时候这无关紧要,但是一旦封闭在一个函数中它就会生效。如果你关闭一个函数内的动画调用,它仍然会引用动画,并且应该有效。
animation = setInterval(function(){ animate(); }, 10);