Animations with HTML5 Canvas in jQuery

If we said it once, we’ll say it again. Recent developments on the Web have made giving a site that extra “wow” effect just that much easier. One of the big additions to HTML5 is the canvas tag. This element creates a space for drawing bitmap images in HTML. The markup for canvas is about as minimalistic as it gets:

<canvas id=”drawingSpace” width=”300″ height=”200″></canvas>

To get any real use out of canvas, you’ll need JavaScript. The following example demonstrates how to create a rectangle:

$(function(){

var rect_ctx = $(“canvas#rect”)[0].getContext(“2d”);

rect_ctx.fillRect(10, 10, 50, 50);

});

The canvas object is selected, and used to get a handle on its context. Then the context is used to draw a rectangle at the point (10, 10) with a width of 50 and a height of 50. The context is an object that contains all of the drawing methods and properties for the canvas. In the previous example, you used the fillRect() method to create a rectangle using the system default color black.

The coordinate system used by canvas has its origin at the top-left corner of the browser window with an increasing x value toward the right and an increasing y value downward. Figure 7-3 illustrates this system.

The strokeStyle is the outline style, and the fillStyle obviously is for everything inside the drawn area. Here are a couple of different rectangles with different fill and stroke styles:

$(function(){

var ctx = $(“canvas#c1”)[0].getContext(“2d”);

ctx.fillStyle = “rgb(0,150,0)”;

ctx.strokeStyle = “rgb(200,0,0)”;

ctx.fillRect(0,0,150,150);

ctx.fillStyle = “rgb(100,100,0)”;

ctx.fillRect(150,150,150,150);

});

You can also draw connected lines. First you map out the path, and then do the actual drawing.

ctx.beginPath();

ctx.moveTo(1,1);

ctx.lineTo(10,10);

ctx.stroke();

ctx.closePath();

To get a good primer on the canvas tag we recommend the canvas chapter of Mark Pilgrim’s, “Dive Into HTML5.” You can find it at http://diveintohtml5.info/canvas.html.

In the next example, you redo the same box animation, but this time you use canvas instead of a div. Even though this example is just a simple black box, consider that it could be a much more complex drawn object.

<!DOCTYPE html>

<html>

<head>

<style type=”text/css”>

canvas {

width:100px;

height:100px;

top:0;

left:0;

position:absolute;

}

</style>

<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

<script type=”text/javascript”>

$(function(){

var rect_ctx = $(“canvas#rect”)[0].getContext(“2d”);

rect_ctx.fillRect(0, 0, 50, 50);

$(document).click(function(){

$(“#rect”).animate({

left :  ‘+=800px’}, 200);

});

});

</script>

</head>

<body>

<canvas id=”rect”></canvas>

</body>

</html>

Code snippet is from canvas.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *