Apr
18
2009

 

This is a guide of how to use HTML 5 Canvas, as well as some JavaScript/css tricks to enable drawing on top of a web page. To see the result of this tutorial, open http://permadi.com/blog/?p=383.

Canvas introduction is covered here and here.

You need a browser that support Canvas such as Firefox 3 to run the examples.

Creating The Canvas Object

You can add a canvas element into your html programatically or as part of the html.
To create a Canvas as html element, you can use <canvas > tag, like below for example:

For example, below I created a 300 x 300 canvas with a black outline.

<canvas id="canvas1" width='300' height='300' style="border:1px solid #000;"/>

To create a Canvas programatically with JavaScript, use something like this:

[c]document.createElement('canvas');[/c]

To specify the dimensions, you should set the Canvas’s width and height, as well as the style’s width and height. If you only specifies the style width and height, then the canvas will be stretched to fit the parent’s (container’s) div.

[c]
    myCanvas=document.createElement('canvas');
    myCanvas.style.width = containerDiv.offsetWidth+'px';
    myCanvas.style.height = containerDiv.offsetHeight+'px';
    // You must set this otherwise the canvas will be streethed to fit the container
    myCanvas.width=containerDiv.offsetWidth;
    myCanvas.height=containerDiv.offsetHeight;
[/c]

Drawing On The Canvas

When first created, the Canvas will be blank and transparent. You can draw on it using commands such as lineTo, fillRect, etc. For example, this code below draws a rectangle on coordinate (20,20) with width and height of 100.

[c]
  var myCanvasObject = document.getElementById('myCanvas');
  var context = myCanvas.getContext('2d');
  context.fillRect(20,20, 100, 100);
[/c]

Notice how we retrieve the Canvas element using getElementById(canvasId). Also notice that to draw into the canvas, you need to retrieve the “context” of the Canvas, using getContext.

The result of that code is something like this. The black outline is from the canvas, which was created with this (same as the example in the previous section except, here, I set the background-color to yellow):

<canvas id="canvas1" width='300' height='300' style="border:1px solid #000;"background-color=#FFFF00 />

See https://developer.mozilla.org/samples/canvas-tutorial/2_1_canvas_rect.html for more examples.

Continued in Part 2

One Response to “Using HTML 5 Canvas To Draw Over A Web Page – Part 1”

  1. [...] Part I: http://www.permadi.com/blog/2009/04/using-html-5-canvas-to-draw-over-a-web-page/ [...]