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

时间:2013-04-03 18:46:46

标签: javascript html5 animation canvas

我创建了一个简单的画布动画,我听说使用'request animation frame'比'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); 

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:5)

始终使用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);
      };
    })();

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

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

    以下是示例框架代码:

        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/

答案 1 :(得分:1)

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

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

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

  1. 将在页面处于非活动状态时提供CPU限制
  2. 为您提供了requestAnimationFrame提供的幕后优化功能。
  3. 可以在here找到关于请求动画帧的好页面。