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.

height

Use to set the height of the graphics.


width

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">
</canvas>

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>

<html>

  <head>

    <meta charset="UTF-8">

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

    <meta name="viewport" 
    content="width=device-width,initial-scale=1.0">          

    <title>Canvas Blog</title>

  </head>

  <body>

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

            style="border:1px solid black"

    </canvas>

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

  </body>

</html>

Output:

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.


strokeText(text,x,y)

It draws unfilled text on the canvas.

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

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

</canvas>

<script>

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

Output:

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 :

moveTo(x,y)

This property defines the starting point of the line.

lineTo(x,y)

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;">
</canvas>

<script>
  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);
    ctx.stroke();

   }
  draw();
</script>

Output:

Stay tuned for more updates from PLG Works!

Gopal Jasani

Gopal Jasani