繁体   English   中英

为什么此函数在运行时会给出错误,但如果复制到控制台却不会给出错误?

[英]Why does this function give an error when run, but not if copied to console?

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

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

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

animation = setInterval(animate, 10);

当您将其作为字符串传递时,settimeout调用从动画调用中删除范围。 何时设置动画是全局的并不重要,但是一旦包含在函数中就可以了。 如果关闭函数中的动画调用,它将仍然具有动画引用,并且应该可以工作。

animation = setInterval(function(){ animate(); }, 10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM