3 Simple Steps to Draw HTML Canvas

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 an ID attribute with the specified value.
 
Syntax
  1. var canvas=document.getElementById(“newCanvas”) ;   
Here ID is “newCanvas” and canvas is a 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.
 
Syntax
  1. var context=canvas.getContext(“2d”);     
Step 3: Drawing on the canvas
 
Now, in the final step, you can draw what you want on the canvas by setting the 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.
 
Syntax
  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;"></canvas>    
  4.         <script>      
  5.       var canvas = document.getElementById("newCanvas");      
  6.       var context = canvas.getContext("2d");      
  7.       context.fillStyle = "lightgreen";      
  8.       context.fillRect(10,10,180,100);      
  9.    </script>    
  10.     </body>    
  11. </html>    
Output:
 
a 
 
Likewise 
  
s    
  
Similarly, you can draw these also by applying other canvas methods.
 
d
 
Thank you, keep learning and sharing.
Next Recommended Reading CANVAS in HTML5 (Best Drawing Surface)