Adding and Drawing on Canvas in HTML5

 You can add canvas to your HTML5 page with the help of HTML5 tag called canvas. See example below

<canvas height="100" width="100"> </canvas>

This HTML5 element can have attributes just like any older HTML tag. In order to put a border around this canvas, we’ll need to add style to this tag

<canvas height="100" width="100"  style="border: 1px solid;"> </canvas>

HTML5 canvas needs to be identified in order for our JavaScript find canvas as object on our page.

<canvas id="sample" height="100" width="100"  style="border: 1px solid;"> </canvas>

Let’s draw something on our canvas in order to make it useful to our users. We’ll draw a simple line for this example.



 function drawLine()


   var myCanvas = document.getElementById('canvas');

   var myContext = canvas.getContext('2d');


   myContext.moveTo(30, 90);

   myContext.lineTo(90, 30);




  window.addEventListener("load", drawLine, true);



This code is not overly complicated if you already know JavaScript. However, if you are new to JavaScript then you may read about it online. In brief, we set two points on our canvas and called on stroke() method to draw a line between two points. 

Featured pages


Learn about HTML5 architecture, design principles and patterns on HTML5 Overview Tutorial. Become …


Learn about HTML5 tags and discover a new list of HTML5 tags. Find out about HTML5 tags support by…


 Learn HTML5 development techniques, tips and tricks on our website. Find out what is required…

Date Time Picker

HTML5 forms use date and time controls regularly. HTML5 date and time controls are used by booking …