DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Paint on a canvas like Van Gogh

Paint on a canvas like Van Gogh

Giorgio Sironi user avatar by
Giorgio Sironi
·
Oct. 12, 10 · Interview
Like (0)
Save
Tweet
Share
8.80K Views

Join the DZone community and get the full member experience.

Join For Free

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.beginPath();
        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;
        context.stroke();
    };

    // 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);
}
</script>
JavaScript library Element

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is API-First?
  • What Is JavaScript Slice? Practical Examples and Guide
  • Introduction to Container Orchestration
  • mTLS Everywere

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: