3 Simple Steps to Draw HTML Canvas

This blog will help you to learn about HTML canvas drawing in 3 simple steps.

Drawing HTML canvas

HTML canvas has various methods for drawing paths, circles, boxes, shapes, texts, adding images. The HTML <canvas> has only a container of graphics that can be used to draw the graphics that can be done by scripting (JavaScript).

The following are the three simple steps you need to draw the HTML canvas.

Step 1: Finding the canvas element

The first thing you have to do is that, find the canvas element using the HTML DOM (Document Object Model: root node of HTML document) method getElementById().

The getElementById() method returns the element that has ID attribute with the specified value.


  1. var canvas=document.getElementById(“newCanvas”) ;  
Here ID is “newCanvas” and canvas is variable name.

Step 2: Creating a drawing object

Now, you need a drawing object for the canvas. The getContext() method used to returns an object that provides methods and properties for drawing on the canvas.


  1. var context=canvas.getContext(“2d”);  
Step 3: Drawing on the canvas

Now, in final step you can draw what you want on the canvas by setting fill style of the drawing object to the various colors. The fillStyle is a property that can be a CSS color, a gradient, or a pattern and the default color for fillStyle is black. The fillRect(x, y, width, height) is a method used to draw a rectangle filled with fillStyle on the canvas.


  1. Context.fillStyle=”green”;  
  2. Context.fillRect(0,0,150,20)  
Samples of canvas drawing with JavaScript:

You can draw paths, circles, boxes, shapes, texts, adding images, etc. on the canvas.

  1. <html>  
  2. <body>  
  3.    <canvas id="newCanvas" width="200" height="100" style="border:1px solid green;">  
  4.    </canvas>  
  5.    <script>  
  6.       var canvas = document.getElementById("newCanvas");  
  7.       var context = canvas.getContext("2d");  
  8.       context.fillStyle = "lightgreen";  
  9.       context.fillRect(10,10,180,100);  
  10.    </script>  
  11. </body>  
  12. </html>  



Similarly you can draw these also by applying other canvas methods.

Thank you, keep learning and sharing.

Ebook Download
View all
View all