How to perform Canvas drawing using Javascript?

We can draw objects, text and perform animations in Canvas using Javascript. We can use the  id  attribute of the canvas element to reference it in script file. We can make use of HTML DOM method:  document.getElementById('someId')  to access the canvas element and perform our drawing. As canvas element is just a container, in order to draw something in it we have to create a drawing object. This is done by  getContext('2d')  object. This is a built-in html object that helps us to draw objects within canvas by using its methods and properties.

Following code snippet creates a simple canvas drawing using javascript.

The  fillRect(x,y,width,height) method draws a rectangle from a point x and y with a specified by width and height . By default, the canvas is filled with black colour. In order to change it, we have to use the  fillStyle  property and change the default black colour.

 

 

Leave a Reply