HTML5 Canvas: Animation
Jakob Jenkov |
To draw animations on an HTML5 canvas you need to draw and redraw the frames of the animation on the canvas. You need to do so really quickly to make the many images look like an animation.
To get the best performance for your animation, you should use the requestAnimationFrame
call back function on the window
object. You call this function and pass as parameter
another function to be called when the browser is ready to draw the next frame in the animation.
By letting the browser signal your application when the browser is ready to draw the next frame,
the browser can enable hardware acceleration for your animation, as well as coordinate the frame
redrawing with other redrawing activities in the browser. The overall experience should be a lot
better, than if you use the setTimeout()
function in JavaScript to time the drawing
of the animation frames.
Here is a code example:
function animate() { reqAnimFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame ; reqAnimFrame(animate); draw(); }
This animate()
function first gets a reference to the requestAnimationFrame()
function. Notice that this function may have different names in different browsers. The variable
reqAnimFrame
is set to whatever of these possible functions that is not null.
Second, the reqAnimFrame()
function is called, passing the animate()
function
as parameter. Thus, when the browser is ready to draw the next frame, the animate()
function
is called.
Third, the animate()
function calls the draw()
function. The draw()
function is not displayed in the example above. What it should do is, to first clear the canvas (or as much
of it as you need to clear), and then draw the next frame of the animation.
One more thing that is not shown in the example above is, that the animate()
function should
be called once to start the animation. If not, the requestAnimationFrame()
function is never
called, and the animation loop never started.
Here is an example animation that moves a single rectangle across the canvas:
And here is the code that created it:
var x = 0; var y = 15; var speed = 5; function animate() { reqAnimFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame ; 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();
Tweet | |
Jakob Jenkov |