LearnHow to Draw with HTML 5 Canvas

writes on September 9, 2009

Share with your friends


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


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


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

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

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:


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:


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


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

This is what the finished frame looks like:


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.


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

71 Responses to “How to Draw with HTML 5 Canvas”

  1. 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. 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. 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. Hi…good post guys…thanks for sharing..

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

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

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

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

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


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

  11. Chistosa on March 19, 2010 at 1:20 am said:

    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.

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

  13. ManifestStefany on April 29, 2010 at 3:07 pm said:

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

  14. Ashbind P on June 3, 2010 at 7:30 am said:

    Great!. What about Compatiblity for HTML 5?

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


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

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

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

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

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

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

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

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

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

  25. useful post…thanks

  26. Anonymous on December 17, 2010 at 6:35 am said:


  27. Eric Rowell on January 10, 2011 at 6:57 am said:

    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.

  28. Hi,

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

    Thanks for the help.

  29. Meridius on January 19, 2011 at 8:47 am said:

    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…

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

  31. its good. we wait visit us..

    all internet projects here.


  32. 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!)


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

  34. PixelCut on April 21, 2013 at 11:59 am said:

    WebCode is a drawing app that instantly generates HTML5 Canvas drawing code for you. http://www.webcodeapp.com

  35. HTML Canvas Studio on August 1, 2013 at 8:28 am said:

    A great free online tool for generating HTML Canvas scripts by drawing.

    You can use it for easy learning and developing Canvas elements.


  36. I use creately to create or draw diagrams. Its an online diagram software that supports real-time collaboration.

  37. 人気スーパーコピーブランド時計激安通販専門店私達は長年の実体商店の販売経験を持って、先進とプロの技術を持って、高品質のスーパーコピー時計づくりに 取り組んでいます。最高品質のロレックス時計コピー、カルティエ時計コピー、IWC時計コピー、ブライトリング時計コピー、パネライ時計コピー激安販売中商品の数量は多い、品質はよい。海外直営店直接買い付け!★ 2015年注文割引開催中,全部の商品割引10% ★ 在庫情報随時更新! ★ 実物写真、付属品を完備する。 ★ 100%を厳守する。 ★ 送料は無料です(日本全国)!★ お客さんたちも大好評です★ 経営方針: 品質を重視、納期も厳守、信用第一!税関の没収する商品は再度無料にして発送します
    人気スーパーコピーブランド時計激安通販専門店私達は長年の実体商店の販売経験を持って、先進とプロの技術を持って、高品質のスーパーコピー時計づくりに 取り組んでいます。最高品質のロレックス時計コピー、カルティエ時計コピー、IWC時計コピー、ブライトリング時計コピー、パネライ時計コピー激安販売中商品の数量は多い、品質はよい。海外直営店直接買い付け!★ 2015年注文割引開催中,全部の商品割引10% ★ 在庫情報随時更新! ★ 実物写真、付属品を完備する。 ★ 100%を厳守する。 ★ 送料は無料です(日本全国)!★ お客さんたちも大好評です★ 経営方針: 品質を重視、納期も厳守、信用第一!税関の没収する商品は再度無料にして発送します http://www.newkakaku.net/boq1.htm

  38. 激安 ブランドスーパーコピー新しいものを販売しています。ルイルイヴィトンコピー、グッチコピー、シャネルコピー、ブランドコピー、ブランドスコピー、ブランドコピー時計などルイヴィトンコピー 激安 ブランド、スーパーコピー、代引き対応、レプリカ、安心通販ルイヴィトン偽物、シャネル偽物、グッチ偽物、エルメス偽物、クロエ偽物、カルティエコピー、オメガコピー、IWCコピー楽天ヴィトンコピー屋
    最も美しいスーパーコピー,超格安ブランド時計コピー激安通販専門店!ブランド品に憧れて、予算オーバーし、諦めなければならないことがありましたか。スーパーコピー品が一番いいチョイスだ思います。少しのお金でも、世界中一番人気を持つブランド品、貴族しか買えない贅沢品がゲットできます。素敵な外観と実用性に優れたブランド コピー バッグ,,スーパーコピー財布,スーパーコピー 代引き,エルメス コピー,ルイヴィトン 財布、ルイヴィトン バッグ、ベルトなどの逸品はお客様に提供します。誰でもブランド品を手に入れられるのは弊社の経営理念です。当店の最大目標はお客様が安心してお買い物が出来き、お客様の頼りになるお店を目指す事ことです。お洒落な貴方はきっとこのチャンスを見逃しなくよ! http://www.ooowatch.com/kabann/dior/index.html

  39. 秋冬物もかなりGOODです!最初はベストから。29081568のモンクレールダウンベストをおすすめ!
    スーパーコピー、スーパーコピーブランド(N級品)激安通販専門店世界一流ブランドコピー 財布、スーパーコピー 商品、激安ブランドコピー 。 ヴィトンコピー 、 ミョウミョウコピー 、シャネルコピー 、エル メスコピー 品格安通販。商品は全て最高な材料 と優れた技術で造られて、正規と比べて、品質が無差別です!人気ブランド.. http://www.brandiwc.com/brand-47-copy-0.html

  40. スーパーコピーブランド弊社は安心と信頼のスーパーコピーブランド (N級品)専門店です!全国送料無料!日本一流品質のスーパーコピー時計、ブランド財布コピー、ブランドバッグコピー新作最新入荷!ロレックススーパーコピー,ウブロ スーパーコピー,ブランド時計 コピー,ブランド スーパーコピー,コピーブランド 通販,スーパーコピー 財布その他の世界一流ブランドコピーを取り扱っています。商品は全て最高な材料と優れた技術で造られて、正規と比べて、品質が無差別です!人気時計コピー、N級ブランドコピーのお求めはぜひ当店へ。弊社は正規品と同等品質のブランドコピー品を低価でお客様に提供します
    スーパーコピーブランド格安販売店はこちらへ!品々の激安価格に持ったスーパーコピーブランド 代引きの新作はお客様に提供されます。安心、迅速、確実、お客様の手元にお届け致します。★弊社は9年の豊富な経験と実績を持っております。★一流の素材を選択し、精巧な作り方でまるで本物のようなな製品を造ります。★品質を重視、納期も厳守、お客様第一主義を貫きは当社の方針です。★驚きの低価格で商品をお客様に提供致します!★早速に購入へようこそ! http://www.msnbrand.com/brand-copy-IP-33.html

  41. 2015年の新素材-新作!高品質 腕時計高品質の追求 超N品を良心価格で提供詳しくは以下のようなブランドがあります。HERMES(バッグ、財布、時計) CHANEL(バッグ、財布、時計)LOUIS VUITTON(バッグ、小物、財布、時計) BVLGARI(財布、時計)Christian Dior(バッグ、財布) COACH(バッグ、財布)GUCCI(バッグ、財布) ROLEX(時計)OMEGA(時計) IWC(時計)FRANCK MULLER(時計) HUBLOT(時計)クロエ CHLOE バッグなどです。ご不明点が ございましたらお気軽にお問い合わせください
    100%実物写真ですし、品質が完璧です!”スーパーコピーブランド財布激安 偽物財布激安コピー ルイヴィトン財布偽物,偽物財布コピーエルバーキンコピースーパーコピー財布ブランド財布コピーブランドコピー激安バレンシアガ スーパーコピー激安ロレックス スーパーコピー時計ブランド財布激安 偽物財布激安コピー ルイヴィトン財布偽物,偽物財布コピーブランド激安市場-jck35販売:ブランド財布コピー,激安ブランド,財布コピー,偽ブランド,偽 ブランド財布,偽物ブランド財布,ブランドコピー,ヴィトンコピー,ルイヴィトン財布偽物, シャネル財布コピー,グッチ財布コピー,エルメス財布偽物,D&G 財布コピー,ボッテガ 財布 .2013年新作スーパーコピーロレックス,スーパーコピーロレックス時計通販スーパー コピー品その他の世界一流ロレックススーパーコピー時計品を扱っています。 ホームページをクリックして商品をご覧下さい.ロレックスコピー,業界No.1人気スーパーコピーロレックス腕時計専門販売ロレックスコピー(ROLEXスーパーコピー)のロレックス レプリカ販売専門店です。すべての商品は品質2年無料保証です,ロレックス デイトジャスト 偽物,人気満点ロレックス コピーn級品新作大特集 http://www.gginza.com/wallet/louisvuitton/index_5.html

  42. Anonymous on December 17, 2010 at 6:36 am said:


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

  44. Anonymous on December 17, 2010 at 6:37 am said:

    fuck u

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

  46. Jing3142 on April 20, 2011 at 5:29 pm said:

    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

  47. 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 ;-).

Leave a Reply

Learn to code with Treehouse

Start your 14 day free trial today and get access to hundreds of video courses in web development, design and business!

Learn more