HTML5 Canvas Tag

The HTML Canvas tag <canvas> is used to draw graphics on your web page using javascript. It works as a container for your graphics. We can draw actual graphics using javascript. We can draw various drawings like boxes, circles, text, images, etc.
There are two main attributes of the <canvas> tag  Height and Width.


Use to set the height of the graphics.


Use to set the width of the graphics.

Here is the example of the  <canvas> tag:

<canvas width="200" height="100" style="border:1px solid black">

Now let’s see how we can draw graphics using javascript:

The Below code shows how we can draw a circle using canvas graphics:-

<!DOCTYPE html>



    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" 

    <title>Canvas Blog</title>



    <canvas id="circle" height="250" width="250" 

            style="border:1px solid black"


      var c = document.getElementById("circle");
      var cx = c.getContext("2d");
      cx.arc(100, 100, 70, 0, 3 * Math.PI);




Canvas tag can also be used to draw text on the web page. There are various properties and methods defined to draw text. Some properties are font property, fillText method, strokeText method, etc.

Font Property

It defines the font property of the text

fillText(text, x, y)

It draws filled text on the canvas.


It draws unfilled text on the canvas.

<canvas id="text" width="350" height="100" 

        style="border:1px solid #d3d3d3;">



   var c = document.getElementById("text");
  var ctx = c.getContext("2d");
  ctx.font = "20px Arial";
  ctx.fillText("This is a Demo", 20, 60);


Here, we have used the fillText method.

You can also draw lines on the canvas. There are two methods you can use to do so :


This property defines the starting point of the line.


This property defines the ending point of the line.

The below example shows how to draw a straight line :

<canvas id="line" height="400" width="500"

        style="border:1px solid #d3d3d3;">

  function draw() {
    const canvas = document.querySelector('#line');
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'brown';
    ctx.lineWidth = 3;
    ctx.moveTo(100, 100);
    ctx.lineTo(200, 100);



Stay tuned for more updates from PLG Works!

Gopal Jasani

Gopal Jasani