HTML Canvas Tutorial: Learn Canvas in 10 Minutes

, , …,

Here's a simple canvas.

We paint a rectangle, a line, a text, and a arc.

Here's the HTML:

<canvas id="i02434" width="100" height="100"></canvas>

Here's the CSS, we just added a border:

canvas#i02434 {border:solid thin gray}

Here's the JavaScript:

function ff() {

    // get the canvas HTML element
    var yy = document.getElementById("i02434");

    // create a “context” (painting area). (there's no 3D as of 2013-08-06)
    var xx = yy.getContext("2d");

    // paint a rectangle
    xx.fillRect(50, 25, 15, 10); // x, y, width, height

    // draw some lines
    xx.moveTo(9,9);             // move point to
    xx.lineTo(20,20);           // draw line to here
    xx.strokeStyle = "#ff0000"; // specify color
    xx.stroke();                // actually draw it

    // paint a text
    xx.fillText("abc", 20, 70);

    // paint a arc
    xx.moveTo(70, 60);          // move point to
    xx.arc(70, 60, 19, -1, -6, true); // x, y, radius, angle 1, angle 2, counter-clockwise


How to Script Canvas

To script HTML5 canvas, you create a canvas element, set a context (getContext("2d")), then use various drawing or style commands to paint the canvas area. That's about it.

Note that all canvas technology provides is a pixel painting area with JavaScript commands to paint it. It is not aware of what you draw on it. You can think of it as painting on a wall. For example, if you draw a circle, and you want to delete it, you have to draw on top to “cover” it. If you want to move the circle, you have to draw something to “cover” it, then draw another one at the place you want. If you want to detect clicks on the circle, you have to find the click's coordinate, then manually compute whether that coordinate is within the circle.

Canvas is in contrast with SVG. With SVG, every element you create is a object, and can be manipulated, move to front/back, change parameters, or be animated, put “onclick” event on it, and any changes are rendered in real-time. 〔➤ Canvas vs SVG

Now, all you need to know about scripting canvas is the list of drawing commands.

You should know the basics of JavaScript and scripting DOM. See: JavaScript Tutorial.

Canvas Commands

There are not many commands neither. They are of the following types.

Here's a complete list of JavaScript methods of canvas drawing primitives.

Then, there are others that specify color, width, etc.

Cool Canvas Demo


HTML Standard#the-canvas-element

Like what you read? Buy JavaScript in Depth. Thanks.