HTML5 canvas example

April 22, 2011

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.


Pause: 42

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 ...


Source : http://www.redips.net/javascript/html5-canvas-example/

Examples HTML5 canvas example,


Comments

blog comments powered by Disqus