如果你想做逐帧动画的时候,你应该用这个方法。这就要求你的动画函数执行会先于浏览器重绘动作。通常来说,被调用的频率是每秒60次,但是一般会遵循W3C标准规定的频率。如果是后台标签页面,重绘频率则会大大降低。
var canvas=document.getElementById("canvas"); var ctx=canvas.getContext('2d'); var running=false;// get requestAnimationFrame function AFrame(callback){ return window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } var raFrame=AFrame(); var raf; var ball={ x:100, y:100, vx:5, vy:1, 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 clear(){ ctx.fillStyle=ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(0,0,canvas.width,canvas.height); } function draw(){// ctx.fillStyle = 'rgba(255,255,255,0.3)';// ctx.fillRect(0,0,canvas.width,canvas.height);// ctx.clearRect(0,0,canvas.width,canvas.height);//每次画之前清除上一次的 clear(); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf= raFrame(draw); console.log("运行") } canvas.addEventListener('mousemove',function(e){ if(!running){ clear(); ball.x = e.clientX; ball.y = e.clientY; ball.draw(); }// raf=raFrame(draw); }); canvas.addEventListener("click",function(e){ if (!running) { raf=raFrame(draw); running = true; } }); canvas.addEventListener('mouseout',function(e){ window.cancelAnimationFrame(raf); running = false; }); ball.draw();