如何从'SetInterval'切换到'请求动画帧'

Nuc*_*eus 2 javascript html5 animation canvas

我创建了一个简单的画布动画,我听说使用'请求动画帧'比'setinterval'更好,但我不知道怎么做?

这就是目前的样子:

http://jsfiddle.net/rC7zJ/
var width = 48;
var height = 87;
var speed = 100; //ms
var frames = 1; // Total frames - 1, as frame start from 0 not 
var currentFrame = 0;

canvas = document.getElementById("CanvasAnimate");
ctx = canvas.getContext("2d");
imageTadPole = new Image()
imageTadPole.src = 'https://dl.dropbox.com/u/19418366/tadpole.png';

function draw(){
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(imageTadPole, width * currentFrame, 0, width, height, 0, 0, width, height);

    if (currentFrame == frames) {
        currentFrame = 0;
    } else {
        currentFrame++;
    }
}

setInterval(draw, speed); 
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

mar*_*rkE 6

始终使用Paul Irish为requestAnimationFrame提供的跨浏览器垫片

    window.requestAnimFrame = (function(callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
      function(callback) {
        window.setTimeout(callback, 1000 / 60);
      };
    })();
Run Code Online (Sandbox Code Playgroud)

然后只需编写一个动画函数:

  1. 更新驱动动画的变量(位置,速度,颜色变化等)
  2. 使用canvas'上下文绘制当前帧
  3. 通过重新调用requestAnimFrame,使动画在下一帧保持活动状态

这是示例框架代码:

    function animate() {

      // update animation variables
      X+=20;
      Velocity +=10;

      // clear the canvas and draw the current frame
      // based on the variables you just updated
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.rect(x,y,75,50);

      // request new frame to keep the animation going
      requestAnimFrame( animate );
    }
Run Code Online (Sandbox Code Playgroud)

以下是如何限制动画(如FPS - 但不是):

// set a countdown "throttle" that will slow animate() down by 4X
var notEveryTime=3;

function animate() {

  // if notEveryTime hasn't counted down to 0
  // then just don't animate yet
  if(--notEveryTime>0){ return; };

  // update animation variables
  X+=20;
  Velocity +=10;

  // clear the canvas and draw the current frame
  // based on the variables you just updated
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.rect(x,y,75,50);

  // request new frame to keep the animation going
  requestAnimFrame( animate );

  // reset notEveryTime
  notEveryTime=3;

}
Run Code Online (Sandbox Code Playgroud)

而且不要读Anreas'良好的建议:http://paulirish.com/2011/requestanimationframe-for-smart-animating/