I want to be able to pause animation and restart it when I need. To achieve this I added 'click' event listener. So far I can pause it but when I try to resume it I am getting this:

Uncaught ReferenceError: animate is not defined

my code:

var canv = document.getElementById('canv'),
ctx = canv.getContext('2d');
var x = 10,
y = 10;
var dx = 1,
dy = 3;
var running = false;
var anim;

var fps = 60;
var delay = 1000 / 60;

function draw() {
    ctx.clearRect(0, 0, canv.width, canv.height);
    ctx.save();
    ctx.translate(x, y);
    ctx.beginPath();
    ctx.arc(0, 0, 5, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
}

function move() {
    x += dx;
    y += dy;

if (x >= canv.width || x <= 0) {
    dx = -dx;
}
if (y <= 0 || y >= canv.height) {
    dy = -dy;
}
}
var start = 0;

(function animate() {
    running = true;
    var current = new Date().getTime(),
    delta = current - start;

if (delta >= delay) {
    move();
    draw();
    start = new Date().getTime();
}

anim = requestAnimationFrame(animate);
})();

window.addEventListener('click', function() {
    if (running == true) {
    cancelAnimationFrame(anim);
    running = false;
} else {
    anim = requestAnimationFrame(animate);
    running = true;
}
});

what is wrong? Why can't I call animate function? As far as I know it's declared in global scope, so why does it say that it is not defined? I don't get it.

fiddle: http://jsfiddle.net/X9qt7/2/

有帮助吗?

解决方案

You are actually not defining animate() in global scope but as an expression which will never be available from parent. rAF works in the loop inside because it's in animate()'s child scope inside the expression and can reference it.

To fix:

function animate() {
    running = true;
    var current = new Date().getTime(),
        delta = current - start;

    if (delta >= delay) {
        move();
        draw();
        start = new Date().getTime();
    }

    anim = requestAnimationFrame(animate);
}
animate();

Now animate() will defined in global scope.

其他提示

Just go with:

function animate() {
    ...
    window.animation = requestAnimationFrame(animate);
};
animate();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top