Using the Canvas Element

6/7/2010 12:00 AM By

Right off the bat: this one’s a doozy. We’ll only be touching on the very basics in this post, so if you’d like a more in-depth examination of <canvas>, check out Mark Pilgrim’s Dive Into HTML5. According to the spec, the <canvas> element is “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” More simply, it’s a box on your page that can take JavaScript instructions and draw whatever you’d like.

Initially, it’s empty and invisible, so let’s make life a little easier by starting with this code:

<canvas id="myCanvas" width="300" height="225"></canvas>

That gives you an id that you can add some styles to, so go ahead and add a dotted border to #myCanvas with border:1px dotted; in your CSS. Now you’d see a 300x225px rectangle with a dotted border. Marvelous. From here on out, it’s all JavaScript all the time.

So, first, we need to find our <canvas> in the DOM:

var my_canvas = document.getElementById("myCanvas");

From there, let’s draw some simple shapes. So, let’s create a rectangle using this:

function draw_rec() {
    var my_canvas = document.getElementById("myCanvas");
    var my_context = my_canvas.getContext("2d");
    my_context.fillRect(50, 25, 150, 100);
}

And then attach that function to an onclick handler:

<a href="#" onclick="draw_rec();return false">Click to draw a rectangle</a>

All together now:

<canvas id="myCanvas" width="300" height="225"></canvas>
<a href="#" onclick="draw_rec();return false">Click to draw a rectangle</a>
<script>
function draw_rec() {
    try {
        var my_canvas = document.getElementById("myCanvas");
        var my_context = my_canvas.getContext("2d");
        my_context.fillRect(50, 25, 150, 100);
    } catch(err) {}
}
</script>

Clicking the link draws the rectangle inside your <canvas>. Excellent. But what about this little tidbit:

var my_context = my_canvas.getContext("2d");

Well, every <canvas> has a context, which could be thought of as the drawing dimension. Currently, "2d" is the only option, but some vendors are experimenting with 3-D. We’ll see what the future holds.

Finally, we’ll go through the canvas coordinate system. Think of the canvas as a piece of grid paper (you remember high school geometry, right?), except the grid is invisible. So why don’t we actually use <canvas> to visually represent this? Give this a whirl:

<canvas id="c" width=500 height=375></canvas>
<script>
var c_canvas = document.getElementById("c");
var context = c_canvas.getContext("2d");

// Draw the grid
try {
    /* vertical lines */
    for (var x = 0.5; x < 500; x += 10) {
        context.moveTo(x, 0);
        context.lineTo(x, 375);
    }
    /* horizontal lines */
    for (var y = 0.5; y < 375; y += 10) {
        context.moveTo(0, y);
        context.lineTo(500, y);
    }
    /* draw it! */
    context.strokeStyle = "#eee";
    context.stroke();
} catch(err) {}

// and now some arrows show the axes
try {
/* x-axis */
    context.beginPath();
    context.moveTo(0, 40);
    context.lineTo(240, 40);
    context.moveTo(260, 40);
    context.lineTo(500, 40);
    context.moveTo(495, 35);
    context.lineTo(500, 40);
    context.lineTo(495, 45);

    /* y-axis */
    context.moveTo(60, 0);
    context.lineTo(60, 153);
    context.moveTo(60, 173);
    context.lineTo(60, 375);
    context.moveTo(65, 370);
    context.lineTo(60, 375);
    context.lineTo(55, 370);

    /* draw it! */
    context.strokeStyle = "#000";
    context.stroke();
} catch(err) {}

// A little text to label the arrows & coordinates
try {
    context.font = "bold 12px sans-serif";
    context.fillText("x", 248, 43);
    context.fillText("y", 58, 165);
} catch(err) {}

try {
    context.textBaseline = "top";
    context.fillText("( 0 , 0 )", 8, 5);
} catch(err) {}

try {
    context.textAlign = "right";
    context.textBaseline = "bottom";
    context.fillText("( 500 , 375 )", 492, 370);
} catch(err) {}
}

// And the dots showing the minimum & maximum coordinates
try {
    context.fillRect(0, 0, 3, 3);
    context.fillRect(497, 372, 3, 3);
} catch(err) {}
</script>

Whew! You should see this:

An image of the grid the above code draws

One of the things this clearly demonstrates is how much greater the role of the web developer will be as HTML5 grows into its own and changes HTML web design and development, and just how much more integral JavaScript has become. As is the case with most web design tools, there’s much more to using <canvas>, but we’re just here to get you started. Enjoy!

Tags: ,

Comments are closed.