totn HTML

HTML: <canvas> tag

This HTML tutorial explains how to use the HTML element called the <canvas> tag with syntax and examples.

Description

The HTML <canvas> tag is an HTML5 element that is used as a container to draw graphics such as 2D objects and bitmap images in an HTML document. The actual graphics within this container are drawn using <script> tags. This tag is also commonly referred to as the <canvas> element.

Syntax

In HTML, the syntax for the <canvas> tag is: (example draws a blue bevelled box using <script> tags and displays it within the <canvas> tag)

<body>

  <canvas id="totn_canvas" width="125" height="125"></canvas>

  <script>
    var canvas = document.getElementById("totn_canvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#4B6692";
    ctx.fillRect(25, 25, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);
  </script>

</body>

Sample Output


Attributes

In addition to the Global Attributes, the following is a list of attributes that are specific to the <canvas> tag:

Attribute Description HTML Compatibility
height Height of the canvas in pixels HTML5
width Width of the canvas in pixels HTML5

Note

  • The HTML <canvas> element is found within the <body> tag.
  • The <canvas> tag acts as a container for the graphics. All graphics are drawn outside of the <canvas> tag using a <script> tag with either the canvas scripting API or the WebGL API.

Browser Compatibility

The <canvas> tag has basic support with the following browsers:

  • Chrome 1.0+
  • Firefox (Gecko) 1.5+
  • Firefox for Android 4+
  • Internet Explorer (IE) 9+
  • Edge
  • Edge Mobile
  • Opera 9+
  • Safari (WebKit) 2+
  • Safari Mobile

Example

We will discuss the <canvas> tag below, exploring examples of how to use the <canvas> tag in HTML5, HTML 4.01 Transitional, XHTML 1.0 Transitional, XHTML 1.0 Strict, and XHTML 1.1.