HTML5 canvas example

The canvas is a new HTML5 element and it is used to draw graphs, charts, animations and other sort of graphics. Actually, canvas is a JavaScript controlled 2D drawing area. This example shows how to create simple JavaScript function and draw circles inside canvas tag. Source code can be downloaded from “Download” icon below post title.


Pause:

The main component of this example is draw() JavaScript function (see the code below). ctx (2D rendering context) object is initialized in window.onload and is used to render graphic. fillStyle, beginPath, arc and fill are parts of 2D context API.

function draw() {
    // generate random color
    // see http://www.redips.net/javascript/random-color-generator/
    ctx.fillStyle = rndColor();
    // start drawing
    ctx.beginPath();
    // draw arc: arc(x, y, radius, startAngle, endAngle, anticlockwise)
    ctx.arc(x, y, r, 0, Math.PI * 2, true); 
    // fill circle
    ctx.fill();
    // set X direction
    if (x + dx > width || x + dx < 0) {
        dx = -dx;  
    }
    // set Y direction
    if (y + dy > height || y + dy < 0) {
        dy = -dy;  
    }
    // set radius size
    if (r + dr > radius * 2 || r + dr < radius) {
        dr = -dr;
    }
    // calculate new x, y and r values
    x += dx;
    y += dy;
    r += dr;
    // if "run" variable is true, then set timeout and call draw() again
    if (run) {
        setTimeout(draw, pause);
    }
}

If pause is decreased then animation will be faster. On the other hand, if you click on start button twice then JavaScript engine will start two parallel processes to call draw() function. The result will be twice faster animation regardless to the current pause value.

This page is modification of excellent Canvas Tutorial – Bounce. Tutorial is divided in steps and guides from drawing a circle on canvas to the simple game in last step. Each step includes an editor and is possible to on-line modify JavaScript code – very impressive.

And finally, your browser should be ready for HTML5 to see how this example works. Try with Chrome 10, FireFox 3.6, Opera 11 …

4 thoughts on “HTML5 canvas example

  1. Hi,
    thanks for this fine script. But what’s if I have a specific path the circle must follow? Thanks for your help (if possible). Hvala lega ;-)

  2. @Joe – Canvas is simply said a drawing board – a Coordinate Grid with (0, 0) in upper left corner. This example uses line paths from bound to bound to draw circles. Any other path is possible but you will have to calculate circle centers – for example you can calculalte circle center with Math.sin(x) or Math.cos(x) …

    Thanks!

    PS Pozdrav iz Zagreba!

  3. Hi,
    thank you, I’ll try. And If I’ll have any of the result I need, I’ll write you ;-)

    Pozdrav iz Vicenza (I) – Osijek (HR)

Leave a Comment