2

我创建了一个简单的画布动画,听说使用“请求动画帧”比使用“设置间隔”更好,但我不知道该怎么做?

这是它目前的样子:

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

任何帮助,将不胜感激!

4

2 回答 2

6

总是从 Paul Irish 的 requestAnimationFrame 跨浏览器 shim 开始

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

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

  1. 更新驱动动画的变量(位置、速度、颜色变化等)
  2. 使用画布的上下文绘制当前帧
  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 );
    }

以下是如何降低动画的速度(如 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;

}

并阅读 Anreas 的好建议:http : //paulirish.com/2011/requestanimationframe-for-smart-animating/

于 2013-04-03T19:06:31.870 回答
1

mark 说了什么,但如果你想控制 FPS,请将 requestAnimationFrame 调用包装在 setTimeOur 函数中,如下所示:

var fps = 15;
function draw() {
    setTimeout(function() {
        requestAnimationFrame(draw);
        // Drawing code goes here
    }, 1000 / fps);
}

使用 requestAnimationFrame 是个好主意,即使您正在修复帧速率,因为它

  1. 当页面处于非活动状态时将提供 CPU 节流
  2. 为您提供 requestAnimationFrame 提供的幕后优化。

可以在此处找到有关请求动画帧的好页面。

于 2013-04-03T19:47:39.443 回答