在html5 canvas中绘制图像动画效果,你需要绘制出每一帧的图像,然后在一个极短的时间内从一帧过渡到下一帧,形成动画效果。 示例要在html5画布上绘制动画,您需要在画布上绘制和重新绘制动画的帧。您需要非常快地这样做,以使许多图像看起来像动画。 function animate() { reqAnimFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { var self = this, start, finish; return window.setTimeout(function() { start = +new Date(); callback(start); finish = +new Date(); self.timeout = 1000/60 - (finish - start); }, self.timeout); }); reqAnimFrame(animate); draw(); } animate()函数首先获得对该requestAnimationFrame() 函数的引用。请注意,此函数在不同的浏览器中可能具有不同的名称。将该变量 reqAnimFrame设置为所有这些不为null的可能函数。 <canvas id="ex1" width="500" height="170" style="border: 1px solid #cccccc;"> HTML5 Canvas not supported </canvas> <script>var x = 0; var y = 15; var speed = 5; function animate() { reqAnimFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { var self = this, self.timeout); }); reqAnimFrame(animate); x += speed; if(x <= 0 || x >= 475){ speed = -speed; } draw(); } function draw() { var canvas = document.getElementById("ex1"); var context = canvas.getContext("2d"); context.clearRect(0, 0, 500, 170); context.fillStyle = "#ff00ff"; context.fillRect(x, y, 25, 25); } animate(); </script> |