HTML and CSS Reference
In-Depth Information
call the method
toDataURL
, which saves the
canvas
as an image with a default mime type of png. You can also save in
other formats, such as jpeg and gif, as well by setting the correct mime type.
Animations
Having the
canvas
element handle animations is another huge plus for designers—particularly animators.
Animations can be handled in several different ways in the browser. Listing 4-10 shows the most logical approach in
HTML5-compliant browsers, the
requestAnimationFrame
method.
Listing 4-10.
Using Canvas for Animations
<script>
var canvas = document.getElementById('adCanvas');
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 200, 200);
gradient.addColorStop(0, '#000000');
gradient.addColorStop(1, '#999999');
context.fillStyle = gradient;
var x = 0, y = 0;
var shapeWidth = 50, shapeHeight = 50;
var speed = 12;
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame || window.oRequestAnimationFrame;
reqAnimFrame(animate);
x += Math.round(speed);
if (x <= 0 || x >= canvas.width - shapeWidth) {
speed = Math.round(−speed);
}
draw();
}
function draw() {
context.clearRect(0, 0, 500, 170);
context.fillRect(x, y, shapeWidth, shapeHeight);
}
animate();
</script>
As can be seen in the listing, the
canvas
element handles animations by utilizing
requestAnimationFrame
pretty
easily; it tells the browser you are intentionally trying to animate something. First, grab the
canvas
element and add
its 2D context (nothing new there). Then add some setup vars (variables) to control x, y, width, height, and speed of
the animation. Next, set up a function called
animate
, which calls itself every time the frame is requested and calls the
draw
method.
■
Note
Functions are called methods when they are attached to an object.
Finally, inside the
draw
method are two methods,
clearRect
and
fillRect
, that are responsible for
clearing and drawing the square to the screen. Just remember to include the entire list of vendor prefixes for the
requestAnimationFrame
(for the time being) if you're targeting requirements include all the modern HTML5 browsers.