Curated by Carsonified

Learn with Treehouse

Accessibility, CSS3, Design, Django, HTML & CSS, HTML5, JavaScript, jQuery, NoSQL, PHP, Responsive Web Design, Ruby, Ruby on Rails, Tools, UX, Version Control, WordPress, iOS and more

Article 60

How to Draw with HTML 5 Canvas

By

09 September 2009 | Category: Code, HTML5

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.

Give a Think Vitamin Membership gift subscription to someone

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" width="200" height="200">
<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:

smileyface

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:

cocktail

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";

cocktail-frame-shadow

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:

cocktail-rotated

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:

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:

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="excanvas.js"></script><![endif]-->

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

Other Examples

Follow @thinkvitamin on Twitter Please check out Treehouse

Other Posts You Might Find Interesting

Comments

  • http://www.bradezone.com/ Brade

    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.

  • http://arindamchakraborty.com Chandan

    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…

  • http://www.thecssninja.com/ Ryan

    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.

  • http://www.anieto2k.com/2009/09/10/hola-mundo-en-canvas/ Hola mundo en canvas | aNieto2K

    [...] En Carsonified.com nos muestran un interesante tutorial con el que iniciarnos en el uso de <canvas /> mediante Javascript. [...]

  • http://fastindietpillsreview.com veronycha

    Hi…good post guys…thanks for sharing..

  • http://dtott.com/thoughts/2009/09/10/more-drawing-in-canvas/ More Drawing in Canvas » {Daniel T Ott}

    [...] of HTML5 and canvas, Carsonified has a nice little tutorial to get started with canvas. This article includes a good overview of where you can use canvas [...]

  • http://www.myvmwareservices.com Roger Denton

    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

  • http://identi.ca/notice/9792293 Laura Carlson (lauracarlson) ‘s status on Thursday, 10-Sep-09 17:17:33 UTC – Identi.ca
  • http://www.soberma.com/read-9-20090911 精品阅读(9)20090911 — 寂寞如哥

    [...] 如何用HTML5的Canvas对象进行绘画 【HTML】 http://carsonified.com/blog/dev/html-5-dev/how-to-draw-with-html-5-canvas/ [...]

  • http://ref.amfdesigner.com/2009/09/11/how-to-draw-with-html-5-canvas/ amf | ref » How to Draw with HTML 5 Canvas

    [...] [Via] Link [...]

  • http://yeetorrents.com/news4/2009/09/14/carsonified-%c2%bb-how-to-draw-with-html-5-canvas/ » Carsonified » How to Draw with HTML 5 Canvas – Yee Torrents News 4

    [...] Source:Carsonified » How to Draw with HTML 5 Canvas [...]

  • http://www.elwebmaster.com/articulos/html5-dibuja-utilizando-el-tag-canvas-y-javascript HTML5: Dibuja utilizando el tag Canvas y Javascript – elWebmaster.com

    [...] Fuente: Carsonified [...]

  • http://www.pointx.se/html-5/ HTML 5 | Webbdesign

    [...] En annan rolig guide för HTML 5 är den som Carsonified skrivit om hur du ritar med HTML 5. [...]

  • http://EarnMoneyOnlineHub.com Chandan

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

  • http://blog.kokanovic.org/playing-with-canvas-element/ Кокановић блог » Playing with canvas element

    [...] nice post I found on DZone which summarizes some great examples of canvas usage, you can find it here (examples are at the bottom, if you’re not interested in theory). Another great summary post [...]

  • jamesm

    you should not use that ie code it does not work corretly you should try using the google chrome iframe all you need is a single meta tag and if you want you can add smail script that will saw we have it dont show this frame and it works lots better.

  • Fido

    I’m a cartoonist and will find it extremely hard to ‘code’ my drawings. Will there be an authoring tool like Flash for HTML5? Or does everything literally have to be hand coded. Artistic people and people who have a head for coding are two completely different brains.

  • http://radleymarx.com/2010/02/five-myths-of-html5-vs-adobe-flash/ Radley Marx » Blog Archive » Five Myths of HTML5 (vs. Adobe Flash)

    [...] tools, no animation controls, no tutorials. Nothing! What does exist are various examples of how to write code to create primitive graphics or how to convert graphics from Illustrator to [...]

  • http://www.neonink.co.uk/blog/html5-a-brief-introduction/ HTML5 – A Brief Introduction | Neon Ink

    [...] How to Draw with HTML 5 Canvas HTML5 Canvas and Audio [...]

  • http://www.flashmonkey.co.uk/html5-monkey/ HTML5 Monkey | Flash Monkey

    [...] of Playing around with canvas below are some useful/inspiring links: > HTML5 Canvas Cheat Sheet > How to Draw with HTML 5 Canvas > P01’s Mars Canvas – check out the source code for this > Some cool HTML5 stuff from Dr Doob [...]

  • http://www.flashmonkey.co.uk FlashMonkey

    Thanks for the great tutorial. After reading this I ported a couple of my old flash physics experiments to HTML5:

    http://www.flashmonkey.co.uk/html5/simple-physics/
    http://www.flashmonkey.co.uk/html5/colorwall/

  • http://bob.web.id/2010/03/10/fitur-canvas-di-html-5-unspeakable/ Fitur Canvas di HTML 5, Unspeakable! | bakazero's backstage

    [...] Drawing Canvas – Jamie Newman [...]

  • http://www.gr1innovations.com Trent

    Wow that is very cool. Thank you very much for the tutorial. I am very bad with image manipulation and creation so this well definitely help. It’ll take some practice but I know I can get better.

  • Chistosa

    Flashmonkey, very nice. Simple-physics has great potential for turning into a pool table …
    Just one suggestion – the “get yourself a real browser ;-)” message could be styled so it shows on the black background.

  • http://www.orcsweb.com/blog/brad/will-html5-revolutionize-the-web-experience/ Will HTML5 Revolutionize The Web Experience?

    [...] The new standard is still being worked out, but some of the features working into the standard are a canvas object to allow drawing, video streaming without a plug-in (like Flash or Silverlight), offline data storage, drag-and-drop [...]

  • http://www.cdesign.in cdesign

    it’s good it was very useful for me every one should check it out. good work

  • ManifestStefany

    Thank you for sharing. It’s exactly what I was looking for. :)

  • http://www.creativemanstudio.com/blog/modern-css-layouts-part-2-the-essential-techniques/ Modern CSS Layouts, Part 2: The Essential Techniques | Creative Man Studio

    [...] for the new form elements and attributes to browsers that don’t currently support them.How to Draw with HTML 5 Canvas (Carsonified)Canvas tutorial (Mozilla Developer Center)HTML 5 canvas – the basics (Opera [...]

  • http://defonic.com/2010/05/13/modern-css-layouts-part-2-the-essential-techniques/ Modern CSS Layouts, Part 2: The Essential Techniques « Defonic International Solutions

    [...] How to Draw with HTML 5 Canvas (Carsonified) [...]

  • Ashbind P

    Great!. What about Compatiblity for HTML 5?

  • http://jp.ashigakari.com/ ashigakari

    nice! I might change few site features and apply HTML 5 tech.

    thanks

  • http://jacksonkr.com jackson

    I’ve been working on an opensource framework which basically turns html5 into a flash-like app (for interactive developers). right now it lets you use illustrator as the drawing tool. have a look-see: http://flanvas.com

  • http://writingformoney.com money writer

    HTML 5 is really growing more rapidly than I ever expected. Elance is posting incredible numbers on its growth. I guess this is a good thing but I am still learning the basics of html. : (
    I know I have a lot of catching up to do. Do I have to learn html or can I just skip to HTML 5??

  • http://www.hydroponicgardeningsupplies.net Jim Bruce

    So far I’ve not used Canvas but it looks interesting and I can think of a few possibilities on one of my websites. I heard of the application some time back and did a little research of my own. I did however come across a Cheat Sheet for Canvas, which can be accessed here http://www.selfhtml5.org/wp-content/uploads/2010/07/HTML5_Canvas_Cheat_Sheet.png

  • http://www.sspathania.com ss pathania

    HTML5 help us to make and arrange our blog so it’s nice stuff.

  • http://www.dailymotion.com/video/xa37j3_how-to-make-money-online-3k-a-week_people Amelia

    Nice tutorials. Thanks for sharing. Definitely loads to learn I’m fairly new and the more I learn the more I need to learn : ) Thanks again.

  • Robbie

    I’m an artist. My brain doesn’t work this way. Wouldn’t it be easier to have a GUI application such as Flash where you simply click on a circle icon from the tool palette and just draw the friggen circle. Now it will take me 3 or 4 times as long to do anything.

  • http://www.logoonlinepros.com/ Corporate Logo Design

    Wow its really a very helpful tutorial for me.
    I like this great learning post.
    Keep it up.Nice learning blog.

  • http://twitter.com/brinleyang Brinley Ang

    Doodle.js link is broken. I think its been updated to http://lamberta.posterous.com/doodle-js

  • Alp
  • http://www.engineersinstitute.com/ ies coaching delhi

    Hey its really useful post..thanks some time i just use HTML….

  • http://www.home4sure.com/ Home4sure

    useful post…thanks

  • http://www.webconnecttechnologies.com/ web designing company delhi

    Nice posting…

  • http://navirudra.com naviRudra

    Nice one !!

  • Anonymous

    dfsdfsfsdfsdf

  • Anonymous

    guguguuhtuyu’i

  • Anonymous

    fuck u

  • Lenny

    All web is text similar to this. Later on you will be able to download 3rd party software that will be exactly as you described.. but html 5 is a standard.. not a program. This guide is for web builders more then it is for artists home web site.

  • Eric Rowell

    Another great resource for HTML5 Canvas tutorials is, go figure, http://www.html5canvastutorials.com. It has a great set of tutorials to teach you everything you need to know about the HTML5 canvas from A – Z.

  • http://www.canvasdeluxe.com/ Photos on canvas

    Hi,

    It’s really more useful article to Draw with HTML 5 Canvas.

    Thanks for the help.

  • Meridius

    Can Someone tell me that, is it necessary to have a javascript with a canvas tag???
    or we can just work it out using other html tags within the HTML5 canvas tag…

  • http://designcloud.net Vector logos

    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog.The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.

  • http://twitter.com/HRmyanmar HRM

    thanks

  • http://www.internetprojeleri.com Internetprojeleri

    its good. we wait visit us..

    all internet projects here.

    http://www.internetprojeleri.com

  • Felixius

    I know that I am reading this as at Feb 2011, but it is still (if not more) relevant.

    But… if you use illustrator, I found this (and I am glad!)

    http://visitmix.com/labs/ai2canvas/index.html

  • lalala

    wow, @Robbie, to be an artist oesn’t mean on’t nee to learn anything.
    Actually it will takke 4 or 5 times more, but, you know what? This process is call LEARN, ok, artists also oes it.

  • lalala

    Sorry my “” is f…up:

    wow, @Robbie, to be an artist doesn’t mean don’t need to learn anything.
    Actually it will take 4 or 5 times more, but, you know what? This process is call LEARN, ok? and artists also can do it ;-).

  • http://carsonified.com Ryan Carson

    Thanks! I’ll update now …

  • http://www.eonic.co.uk Wpm

    it is long winded i suppose but more can be done with the elemnts in a similar way to flash.

  • Jing3142

    There is a GUI application now go to https://sites.google.com/site/canvasdraw/introduction for help on how to use it and a link to the application

Badges for Treehouse

Treehouse

Learn iOS, Rails, CSS3, jQuery, Node.js, HTML5, UX and more in less than 8 minutes per day. New videos added regularly. Sign up today and get a free Web Design Toolkit.

Ads Via The Deck

Think Vitamin Radio
Episode #34: Amazon Fire and Responsive Roundtable

Check out our bi-weekly radio show. Covering the hot topics on the web.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

Download Podcast as mp3

Advisory Board

The Think Vitamin Advisory Board in place make sure that you receive the best content possible.