HTML / HTML Tags

HTML <Canvas> Tag

Dec 12, 2022
2 min read
HTML canvas Tag

Definition

The <canvas> element provides scripts with a resolution-dependent bitmap canvas. It can be used for graphs, graphics, and other images.

Example

<canvas width="500" height="300">
  A red rectangle.
</canvas>

<script>
  var canvas = document.querySelector("canvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "red"; // Sets the color
  ctx.fillRect(50, 50, 180, 180);
  /* 
  The first two numbers set the start position (x, y). 
  The second two numbers set the width and height.
  */
</script>

Usage

  • The code snippet in the above example adds a <canvas> element to your web page, along with fallback text describing what the canvas displays.
  • The JavaScript calls the <canvas> element and provides instructions to start drawing on the canvas.
  • The <canvas> element requires a closing tag.

Attributes

The Canvas element supports the Global Attributes, Event Attributes, and the following:

  • height

    The height attribute specifies the height of the coordinate space in CSS pixels. If no value is given, it will default to 150.

  • width

    The width attribute specifies the width of the coordinate space in CSS pixels. If no value is given, it will default to 300.

Best Practices

  • The <canvas> element is just a bitmap and provides no information about the object drawn on it. As it is not accessible, you should avoid using <canvas> elements wherever possible.
  • You should provide the descriptive fallback text as this will be displayed on browsers that have JavaScript disabled, non-supporting browsers, and search engines.
  • While you can size the <canvas> using CSS it is better to use the width and height attributes. When using CSS you may find that the rendered graphics are distorted.

Specification

Browser Support

Desktop

ChromeEdgeFirefoxIEOperaSafari
YesYesYesYesYesYes

Mobile

Android WebviewChrome AndroidFirefox AndroidOpera AndroidiOS SafariSamsung Internet
YesYesYesYesYesYes