HTML <canvas> Tag

The <canvas> tag defines an area on the web page, where we can create different objects, images, animations, photo compositions via scripts.

When working with canvas, it is important to distinguish between concepts such as the canvas element and the context of an element, since they are often confused. The canvas element is what's built into HTML (the DOM node), and the canvas context is an object with its own method and properties for rendering. Context can be 2D and 3D. The canvas element can have only one context.

Syntax

The <canvas> tag comes in pairs, so its content is being written between the opening (<canvas>) and the closing (</canvas>) tags.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head> 
  <body>
    <canvas id="myCanvas">Your browser doesn’t support the HTML5 canvas element.</canvas>
    <script>
      var c=document.getElementById('myCanvas');
      var ctx=c.getContext('2d');
      ctx.fillStyle='#1c87c9';
      ctx.fillRect(10,50,80,80);
    </script>
  </body>
</html>

Result

Example

<!DOCTYPE HTML>
<html>
  <head>
    <title>Title of the document</title>
  </head> 
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
       context.font = '30pt Calibri';
       context.fillStyle = '#1c87c9';
       context.fillText('Canvas Example !', 50, 100);
    </script>
  </body>
</html>

Result

Attributes

Attribute Value Description
height pixels Defines the element height in pixels. Default value - "150"
width pixels Defines the element width in pixels. Default value - "300".

The <canvas> tag supports Global Attributes and the Event Attributes.

Browser support

4+ 9+ 2+ 3.1+ 9+



Related articles