This website uses cookies

We use cookies to personalize content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners who may combine it with other information that you've provided to them or that they've collected from your use of their services. Please read more at our privacy policy page.



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+