Introduction to HTML5 Canvas | HTML CSS Tutor

Introduction to HTML5 Canvas

by: Vivek Marakana

HTML5 emerged with many new element like <video>, <audio>, <canvas> and many new input-types ( like email, date etc. ) which enriched web pages beyond our imagination. HTML5 made itself programmable API so we can make webpage dynamic without needing Flash animation. We will discuss about Canvas API which allows us to be an artist on webpage.

If the <video> element is the poster boy of HTML5, <canvas> element is definitely the Han Solo of HTML5. It’s one of the larger parts of the HTML5 specification, and in fact the canvas API, the 2D drawing context, has been split into a separate document, though the <canvas> element itself is still part of the official HTML5 specs.

The <canvas> element provides an API of 2D drawing – lines, fills, images, text etc etc etc…If you think back to the days of the version of MS Paint, you can imagine its functionality as Paint was build on the basis of canvas (not html canvas).You can visit Mr Doob’s Harmony Canvas Project which is more similar to basic Paint.


Like “With great power, comes great responsibility “, “With new element, comes browser problems.” Same thing applies to <canvas>. Many browser(Of course, it includes IE) does not support canvas API.I any browser does not support any element then being a web developer it’s our lawful duty to display fallback content.

To display fallback content for <canvas>, we can use this code :

   Update your browser to have fun with canvas...!!!

We ca also check for browser support using JavaScript while adding a canvas to HTML file :

   document.getElemnetById("support").innerHTML = "HTML5 canvas is supported.";
} catch(e) {
   document.getElemnetById("support").innerHTML = "HTML5 canvas is not supported by your browser.";

IE Support

If still you want to use canvas in Internet Explorer, you need to use the openproject explorercanvas.You need to include excanvas.js in webpage after checking that current browser is IE.

<!--[if IE]>
   <script src="excanvas.js"></script>

Adding Canvas to Webpage

Now we know the basic needs for canvas and how to handle browser support, so now we’ll see how to add a canvas to a webpage.Adding canvas is pretty easy.We can add it just like we add any-other element(e.g.<div>etc.).The code to add canvas will look like this :

<canvas id="pentagram" style="border:1px dotted;" width="200px" height="200px">

Here come the most interesting part of canvas API.You all will be eager to learn how to draw on canvas (It’s obvious because that’s the main thing for which we use canvas.right ?).

So let’s do something with pristine canvas. We’ll start with my favorite figure – Pentagram.We can draw a pentagran with just few lines of code like this :

function drawDiagonal() { 
   // Get the canvas element and its drawing context 
   var canvas = document.getElementById('diagonal'); 
   var context = canvas.getContext('2d'); 
   // Create a path in absolute coordinates 
   ontext.lineWidth = 4; 
   context.lineJoin = 'round'; 
   context.strokeStyle = 'green'; 
   context.moveTo(50, 140); 
   context.lineTo(100, 40);
   // Stroke the line onto the canvas 
window.addEventListener("load", drawDiagonal, true); 

Did you see that?? How easily we created a pentagram.Now just think about how you would have made it without using canvas?? Creating a pentagram in some graphic software and then save it and include it using <img> element and blah blah blah…OMG it’s so boring and it also increases load of your website.Now you would realize why i said that canvas is Han Solo.

When NOT to use canvas

I know you are wondering why not to use canvas everytime if it’s that much great..but trust me if any other default element is suffice to do any work then USE IT instead of canvas.For example, it’s a very bad idea to use canvas to draw heading dynamically.Instead of it, you should use heading elements(<h1>,<h2>,..) because they are meant for that.But we do not have any element to draw a pentagram so we have used canvas.Got it??

Now i think you got enough for canvas basics so now it’s your turn to dig more into it.I’m sure when you get enough, you will be able to make a good paint editor like SketchPad.

So best of luck guys and yeah if you want to see little demo of canvas – It’s Here…

View Demo Download Demo


15 Comments on “Introduction to HTML5 Canvas”

  • Here we got the 2d context of canvas API.Though 3D canvas is not officially announced but some companies have developed private 3d canvas API.I will come up with good 3D canvas tutorial soon.

  • You can post a comment if you want a tutorial for any particular topic..
    I will cover it in my further posts..

    • Jayden says:

      People nolarmly pay me for this and you are giving it away!

    • "Not to mention that he is unlike the founding fathers in that he hasn't seen a government program and pork that he didn't want to expand"…Well aig not only is your Santorum analysis flawed but I'm wondering if you have something credible (wiki, NYT aren't) to back that last statement about programs and pork…The notes that Santorum had some serious spending problems though…Do you have something different?

    • BION I’m impressed! Cool post!

    • http://www./ says:

      Toooda coleção ainda não chegou, mas a maioria das peças já!Várias peças chegam essa semana e na semana que vem, tipo a calça jeans vermelha e o vestido de borboletas!beijos!

    • vegas world says:

      mamabatranafarabraudelanavreau si eu….. ! daca nu acolo, macar la Sinaia…..! macar in Herastrau!………….. de fapt vreau tihna si curatenia din pozele voastre.chiar trebuia sa plecati de acolo?…. bine ati venit!

  • Lauren says:

    A better magazine theme would make the blog nicer.:)

  • Ashly says:

    It’s hard to find your website in google. I found it on 19 spot,
    you should build quality backlinks , it will help you to rank to google top 10.
    I know how to help you, just type in google – k2 seo tricks

    • Maryellen says:

      With all these silly wesibtes, such a great page keeps my internet hope alive.

    • http://www./ says:

      dit :Nice post at Devenez Super Affilié ! | Article. I was checking constantly this blog and I’m impressed! Very helpful information specifically the last part I care for such information a lot. I was seeking this particular information for a very long time. Thank you and best of luck.

    • http://www./ says:

      I could watch Schindler’s List and still be happy after reading this.

    • http://www./ says:

      I am so jealous of your experience at Natural Gourmet! I am curious though… with all the indulgent treats and tasting food all day… have you gained any weight? This is not mean to be a negative comment in any way, just was interested in knowing! I think i would be 340 lbs. if I baked cookies and pies all day. haha

    • Sal Muoio Sep 18, 2012 – Honestly, from what i have read, i don’t get it. I am an M user. Why should I care about the R lenses? Personally, I don’t care for live-view focusing. GPS should be built in to the camera, not the optional grip. The old naming system used to make sense to me, the new is bound to be confusing. The only changes that matter to me are the new sensor and associated picture quality, which I will be eager to find out more about, in particular in higher ISO’s and the increased dust and moisture resistance.

    • This is just the most beautiful card …its just stunning – lovely colours, papers, design image …oooh the lot – gorgeous…really enjoyed visiting your blogFrom Debby… a new follower!

Leave a Reply to http://www./ Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>