如果你想做逐帧动画的时候,你应该用这个方法。这就要求你的动画函数执行会先于浏览器重绘动作。通常来说,被调用的频率是每秒60次,但是一般会遵循W3C标准规定的频率。如果是后台标签页面,重绘频率则会大大降低。
var canvas=document.getElementById("canvas"); var ctx=canvas.getContext('2d'); // get requestAnimationFrame function AFrame(callback){ window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; return window.requestAnimationFrame(callback); } var raf; var ball={ x:100, y:100, vx:5, vy:2, radius:25, color:'blue', draw:function(){ ctx.beginPath(); ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,true); ctx.closePath(); ctx.fillStyle=this.color; ctx.fill(); } }; function draw(){ ctx.clearRect(0,0,canvas.width,canvas.height); ball.draw(); ball.x+=ball.vx; ball.y+=ball.vy; raf= AFrame(draw); } canvas.addEventListener('mouseover',function(e){ raf=AFrame(draw); }); canvas.addEventListener('mouseout',function(e){ window.cancelAnimationFrame(raf); }); ball.draw();