0

我通常会尽量避免发布大块凌乱的代码,但如果我将它复制到控制台,我真的无法弄清楚为什么这个脚本可以正常工作,但是如果我将它全部包装在一个函数中然后调用该函数,我得到错误,动画未定义。

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
};
4

2 回答 2

2

@Coin_op 答案的替代方法是传递函数引用。

animation = setInterval(animate, 10);
于 2013-06-06T22:39:48.210 回答
1

当您将其作为字符串传递时,settimeout 调用会从 animate 调用中删除范围。当 animate 是全局的时,这无关紧要,但一旦包含在一个函数中,它就可以了。如果您在函数内关闭 animate 调用,它仍然会引用 animate 并且应该可以工作。

animation = setInterval(function(){ animate(); }, 10);
于 2013-06-06T22:37:23.993 回答