Over a million developers have joined DZone.

Paint on a canvas like Van Gogh

DZone's Guide to

Paint on a canvas like Van Gogh

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

I've been reading Dive into HTML 5, an excellent book from Mark Pilgrim which introduces many aspects and innovations of HTML 5. As always, I thought that reading alone could not suffice, and to improve my learning I started exercising with the browser. Practicing is by far a better way to retain information in comparison to simple reading and studying, and forces you to immediately deal with possible issues in coding with these new features.

Thus, today I want to introduce you the <canvas> element, which I have been hacking with for some time. A canvas, as its well-chosen name suggests, is a drawing box that you can fill with what you want. In the case of HTML 5, you can fill it via JavaScript, since the DOM reflects the presence of the element, as if it were a <div> or an <input>, and exposes a set of methods that you can use to draw.

Whether to use the methods directly or through a graphic JavaScript library will be established in the future: for now getting to know what the <canvas> can do, and how to do it, is an acceptable goal. One of the advancements of HTML 5 is requiring less library work, ideally by implementing in the browser the common workarounds present in JQuery, Dojo, and similar products.

So I won't try to code complex examples like bright, moving rainfalls and ancient paintings, but just what you need to get started. The <canvas> element is supported in Firefox 3, where this code has been tested, and many other browsers.

The additions in the DOM

A <canvas> is a block element, with a defined height and width (and also borders, margin and padding if you want.) If you grab the DOM element via JavaScript you can then call any sort of method to draw lines and rectangles, or colorize the picture.

The mechanism does not require JavaScript kung-fu: you can find the element via document.getElementById() like in the case of all other ones, and many properties and methods parameters follow CSS-like values (font, color) as in most of JavaScript bindings.

The canvas has a coordinate system, which starts from the top left corner, like in every computer graphical system (this convention was originally borrowed from televisions).

Once you have access a canvas, you can ask it for his context, which is the main object in a canvas, where you call every single method. Only the 2d context esists yet, but there is the possibility of including multiple functionalities in the future.

Besides the context, another important concept is the path: a set of element with equal styling properties (for example color), that can be drawn and managed at the same time. Whenever you want to start drawing an isolated set of lines, for example with a new fancy color, you probably want to create a new path so that your changes to the stroking style are not reflected to the whole drawing.

In the code sample, also the drawing of rectangles is shown, along with the insertion of text. I have an habit of generating graphs and images on the server side, for example with the PHP gd extension, but having an element available on the client side may force me to change my mind. A client-side solution would also lower the work on the server by eliminating dynamic images creation and caching altogether, and simply return a simple JSON response that can be interpreted by an HTML 5 client. Today, this has to be done with heavy JavaScript or Flash applets, while a canvas-based graph loads almost immediately.

More features

Some features are not treated here, but be aware that they are available in most browsers the have started implementing the draft HTML 5 specification. For example you may draw:
  • arcs and circles
  • Bezier curves
  • images by insertion (already existing ones).

Couple the dynamic drawing capabilities with DOM events and JavaScript handlers, and you obtain great interactivity almost without external libraries. For instance, browser games instantly become easy to code and more performant than their JavaScript-only counterparts.

I have talked too much for today, so let's give you my code. The basic features of <canvas> are exercised here: feel free to paste it in a blank HTML document and start hacking with your browser, or to suggest what to explore next.

<canvas id="drawing" width="400" height="400" style="border: 1px solid black;"></canvas>
<script type="text/javascript">
window.onload = function() {
    var context = document.getElementById('drawing').getContext('2d');

    // draw a 200x300 rectangle with top left vertix at (10, 40)
    //context.fillRect(10, 40, 200, 300);

    // draw a square with top left vertix at (x, y), side l
    draw_square = function(x, y, l, color) {
        context.moveTo(x, y);
        context.lineTo(x + 50, y);
        context.lineTo(x + 50, y + 50);
        context.lineTo(x, y + 50);
        context.lineTo(x, y);
        context.strokeStyle =  color;

    // draw multiple squares
    for (x = 20, y = 20, blue = 0;
         x <= 340;
         x += 10, y += 10, blue += 5) {
            var color = 'rgb(0, 0,' + blue + ')';
            draw_square(x, y, 50, color);

    // a caption
    context.font = "24px sans-serif";
    context.fillText('Black to blue', 50, 300);

    // prepare an oblique gradient and fill a rectangle with it
    // the gradient goes from (0, 0) to (400, 100)
    var gradient = context.createLinearGradient(0, 0, 400, 100);
    gradient.addColorStop(0, '#000');
    gradient.addColorStop(1, 'blue');
    context.fillStyle = gradient;
    context.fillRect(0, 0, 400, 100);

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}