如何阻止回调?

时间:2017-03-01 16:27:10

标签: javascript callback html5-canvas

我有来自Git的画布精灵动画的以下几行。

我只是想知道如何在动画结束后停止动画。

window.requestAnimFrame = (function(callback) { // shim
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

function animate() { // Animation loop that draws the canvas
  context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clear the canvas
  spriteMap.draw(context, 100, 100); // Draw the sprite
  requestAnimFrame(animate); // Run the animation loop
}

https://github.com/IceCreamYou/Canvas-Sprite-Animations

1 个答案:

答案 0 :(得分:1)

cancelAnimationFrame()requestAnimationFrame()返回的请求ID一起使用:

var reqId;

function animate() {
  // ...
  reqId = requestAnimFrame(animate); // returns request ID
}

然后停止:

cancelAnimationFrame(reqId);

如果您依赖于填充,则还必须包含cancelAnimationFrame()的{​​{3}}:

if (!window.cancelAnimationFrame)
  window.cancelAnimationFrame = function(id) {
    clearTimeout(id);
  };