How to Draw with HTML 5 Canvas

Code, HTML5 65 Comments

Among the set of goodies in the HTML 5 specification is Canvas which is a way to programmatically draw using JavaScript.

We’ll explore the ins and outs of Canvas in this article, demonstrating what is possible with examples and links.

spacer

Why Do You Need Canvas?

Canvas can be used to represent something visually in your browser. For example:

  • Simple diagrams
  • Fancy user interfaces
  • Animations
  • Charts and graphs
  • Embedded drawing applications
  • Working around CSS limitations

In basic terms it’s a very simple pixel-based drawing API, but used in the right way it can be the building block for some clever stuff.

What Tools Are at Your disposal?

Drawing tools

  • Rectangles
  • Arcs
  • Paths and line drawing
  • Bezier and quadratic curves

Effects

  • Fills and strokes
  • Shadows
  • Linear and radial gradients
  • Alpha transparency
  • Compositing

Transformations

  • Scaling
  • Rotation
  • Translation
  • Transformation matrix

Getting data in and out

  • Loading external images by URL, other canvases or data URI
  • Retrieving a PNG representation of the current canvas as a data URI

The excellent Canvas cheat sheet is a great reference of the commands available.

Getting Started

To use Canvas, you’ll need two things

  • A Canvas tag in the HTML to place the drawing canvas
  • JavaScript to do the drawing

The Canvas tag is basically an img tag without any data. You specify a width and a height for the drawing area. Instead of an alt attribute, you can enclose HTML within the canvas tag itself for alternative content.

Example of a Canvas tag:

<canvas id="myDrawing" >
<p>Your browser doesn't support canvas.</p>
</canvas>

With a Canvas element in the HTML, we’ll add the JavaScript. We need to reference the Canvas element, check the browser is Canvas-compatible and create a drawing context:

var drawingCanvas = document.getElementById('myDrawing');
// Check the element is in the DOM and the browser supports canvas
if(drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
var context = drawingCanvas.getContext('2d');
//Canvas commands go here
}

Checking for the getContext() method on a canvas DOM object is the standard way of determining canvas compatibility.

The context variable now references a Canvas context and can be drawn on.

Basic Drawing

So, let’s get started with an example to demonstrate the basics. We’re going to draw a smiley face, similar to the one on the Acid2 reference rendering.

If we think about the face as a set of basic shapes, we have:

  1. A circle, with a black stroke and yellow fill for the face.
  2. 2 circles with a black stroke and white fill and with an inner circle of filled green for the eyes.
  3. A curve for the smile.
  4. A diamond for the nose.

Let’s start by creating the round face:

// Create the yellow face
context.strokeStyle = "#000000";
context.fillStyle = "#FFFF00";
context.beginPath();
context.arc(100,100,50,0,Math.PI*2,true);
context.closePath();
context.stroke();
context.fill();

You can see from the above that we start by defining some colours for the stroke and fill, then we create a circle (an arc with a radius of 50 and rotated through the angles of 0 to 2*Pi radians). Finally, we apply the stroke and fill that has been defined previously.

This process of setting styles, drawing to co-ordinates and dimensions and finally applying a fill or stroke is at the heart of Canvas drawing. When we add the other face elements in, we get:

spacer

Download the full source code of the smiley face example

Effects and Transformations

Let’s see how we can manipulate an existing image in canvas. We can load external images using the drawImage() method:

context.drawImage(imgObj, XPos, YPos, Width, Height);

Here’s the image we’re going to play with:

spacer

We’re going to give the image a red frame. For this we’ll use a rectangle and fill it with a radial gradient to give it a bit of texture.

<code>//Create a radial gradient.
var gradient = context.createRadialGradient(90,63,30,90,63,90);
gradient.addColorStop(0, '#FF0000');
gradient.addColorStop(1, '#660000');
//Create radial gradient box for picture frame;
context.fillStyle = gradient;
context.fillRect(15,0,160,140);
//Load the image object in JS, then apply to canvas onload
var myImage = new Image();
myImage.onload = function() {
context.drawImage(myImage, 30, 15, 130, 110);
}
myImage.src = "cocktail.jpg";</code>

To make our portrait look like it’s hung on a wall, we’ll add a drop shadow and rotate the image slightly so it looks at a slight angle.

A drop shadow will need to be applied to the frame.

//Create a drop shadow
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.shadowBlur = 10;
context.shadowColor = "black";

spacer

Download the full source code of the portrait example

To rotate the canvas, we use the rotate() method which takes a value in radians to rotate the canvas by. This only applies rotation to subsequent drawing to the canvas, so make sure you’ve put this in the right place in your code.

//Rotate picture
context.rotate(0.05);

This is what the finished frame looks like:

spacer

Download the full source code of the portrait example

Animation and Physics

Canvas drawings can be animated by repeatedly redrawing the canvas with different dimensions, positions or other values. With the use of JavaScript logic, you can also apply physics to your canvas objects as well.

Example uses:

  • Bouncing Balls by Efeion
  • js-fireworks by Kenneth Kufluk
  • Using canvas in conjunction with the HTML 5 audio element and a Twitter mashup to create the HTML5 Canvas and Audio Experiment

Displaying Fancy Fonts

Canvas can be used as a way of displaying non-standard fonts into a web page as an alternative to technologies like sIFR. The Cufon project is one such implementation. Canvas-based font replacements like Cufon have advantages over sIFR, in that there are fewer resource overheads and no plug-in is required, however there are a few disadvantages:

  • It generates lots of mark-up
  • Fonts are embedded, therefore it breaks the license terms of many fonts
  • Text can’t be selected

Fonts need to be converted for use in Cufon using the tools on the Cufon homepage.

Letting Your Users do the Drawing

JavaScript can interact with mouse and keyboard events, so you can create embedded drawing applications with canvas as the following examples demonstrate:

  • Lightweight sketches with Tiny Doodle by Andrew Mason
  • An MS paint clone in canvas by Christopher Clay

Making up for Browser CSS Deficiencies

Can’t wait for CSS3 support and want to add rounded corners, gradients or opacity without creating lots of images? Projects like jqcanvas add canvas tags behind standard HTML elements to add design to your web page.

Browser Support

The latest versions of Firefox, Safari, Chrome and Opera all enjoy reasonable to good support for Canvas.

What about Internet Explorer?

IE does not support canvas natively (as of IE8), however it has been given some compatibility thanks to the ExplorerCanvas project and is simply a matter of including an extra JavaScript file before any canvas code in your page. You can hide it from other browsers in the standard way, using conditional comments.

<!--[if IE]><script src="/img/spacer.gif">

ExplorerCanvas even extends canvas support to IE6, although it’s not perfect so don’t expect it to render as well as modern browsers that support canvas natively.

Accessibility

Canvas isn’t currently thought of as accessible as there is no mark-up generated or API for textual content to be read. Fallback HTML can be added manually inside the canvas tag, but this will never be good enough to represent the canvas in an accessible way.

Thinking About HTML 5 Canvas Accessibility by Steve Faulkner explains the problems in more detail. There is now a general consensus that accessibility needs to be addressed which has lead to the Protocols and Formats Working Group at the W3C recently opening a discussion into proposals for adding accessibility for Canvas with input from others.

In Summary

Although Canvas adds features to a page, I don’t think it has been particularly well thought out. In many ways it feels like a step into the past and represents a very old-fashioned way of drawing that is inferior to the modern XML-based SVG standard. It is pixel-based, as opposed to the nice vectors of SVG and to draw with it entails writing lots of unmanageable JavaScript. The lack of accessibility is also a big problem.

However, what Canvas has going for it, that SVG doesn’t, is that it can integrate with our existing web pages very easily. We can also work with canvas in much the same way we work with images in web pages.

By looking at the few examples in this article, we can get an idea of the variety of situations that Canvas can be applied to. Although the syntax may be frustrating, Canvas gives us drawing technology that we can use right away to enhance our pages.

Please give your thoughts, link to further examples or any feedback below.

Further Reading

  • Doodle.js – a nice library for working with canvas
  • Canvas Tutorial at Mozilla Developer Center
  • HTML 5 canvas – the basics on the Opera Developer Community

Other Examples

  • Live photo editing with Canvas Photo Demo
  • Live video editing using canvas
  • Online office applications with Mozilla Bespin
  • Super Mario Bros
  • Most of the Chrome Experiments.
spacer

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from HTML, CSS or WordPress.

Start Learning
spacer

Treehouse

Our mission is to bring affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world.

Comments

65 comments on “How to Draw with HTML 5 Canvas

  1. spacer Brade on said:

    Nice overview! It’s true the syntax is quite clunky, but I’m guessing it’s only a matter of time before we have some mootools-like libraries that make working with canvas a painless endeavor.

  2. spacer Chandan on said:

    Nice tutorial..thanks for sharing. As a beginner syntax are little bit difficult for me, but once I practice I think I can draw canvas very well…

  3. spacer Ryan on said:

    All the image manipulation you did in your example can be done with CSS3, box-shadow, transform etc. I think a better example would of been a mini drawing app or showing vector graphics over video.

  4. Pingback: Hola mundo en canvas | aNieto2K

  5. spacer veronycha on said:

    Hi…good post guys…thanks for sharing..

  6. Pingback: More Drawing in Canvas » {Daniel T Ott}

  7. spacer Roger Denton on said:

    VMware is expected to become essential and more popular as databases and applications evolve along with different operating systems. With the data compression and flexiblity of pendrives it will seemingly develop as a valuable developer for the simple formation of a virtual machine surrounding.

    VMWare Service

  8. Pingback: Laura Carlson (lauracarlson) 's status on Thursday, 10-Sep-09 17:17:33 UTC - Identi.ca

  9. Pingback: 精品阅读(9)20090911 -- 寂寞如哥

  10. Pingback: amf | ref » How to Draw with HTML 5 Canvas

  11. Pingback: » Carsonified » How to Draw with HTML 5 Canvas - Yee Torrents News 4

  12. Pingback: HTML5: Dibuja utilizando el tag Canvas y Javascript - elWebmaster.com

  13. Pingback: HTML 5 | Webbdesign

  14. spacer Chandan on said:

    I have done few image manipulation with CSS3. Now I will try to do with HTML 5 Canvas. Nice tutorials. Thanks for sharing it.

  15. Pingback: Кокановић блог » Playing with canvas element

  16. spacer jamesm on said:

    you should not use that