取消动画
要取消对 requestAnimationFrame
的调用,你需要从上次调用时返回的 ID。这是你用于 cancelAnimationFrame
的参数。以下示例启动一些假设动画,然后在一秒钟后暂停它。
// stores the id returned from each call to requestAnimationFrame
var requestId;
// draw something
function draw(timestamp) {
// do some animation
// request next frame
start();
}
// pauses the animation
function pause() {
// pass in the id returned from the last call to requestAnimationFrame
cancelAnimationFrame(requestId);
}
// begin the animation
function start() {
// store the id returned from requestAnimationFrame
requestId = requestAnimationFrame(draw);
}
// begin now
start();
// after a second, pause the animation
setTimeout(pause,1000);