HTML Tutorial: Complete HTML Tutorial
About Lesson

HTML <canvas> Tag


The HTML <canvas> element is a powerful tool that allows developers to draw graphics on the fly using JavaScript. It’s commonly used for creating dynamic visual content like charts, graphs, games, and other interactive visual elements.

Concept

The <canvas> element is a container for graphics where you can draw shapes, lines, images, and even apply animations. It’s like a drawing board where you can use JavaScript to paint anything.

Implementation

Example 1: Drawing a Red Rectangle

<!DOCTYPE html>
<html>
<head>
  <title>Canvas Example</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>

  <script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, 150, 75);
  </script>
</body>
</html>
Sponsored by Google

This code will draw “aptLearn purple” (#696cff) rectangle inside the <canvas> element.

Try it out below:

Loading

Example 2: Another Canvas Example

<!DOCTYPE html>
<html>
<head>
  <title>Another Canvas Example</title>
</head>
<body>
  <canvas id="anotherCanvas" width="300" height="150"></canvas>

  <script>
    var canvas = document.getElementById("anotherCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.fillRect(80, 80, 75, 50);
  </script>
</body>
</html>

This code will draw a green rectangle at a different position on the canvas.

Try it out below.

Loading

Attributes

Attribute Value Description
height pixels Specifies the height of the canvas. Default value is 150
width pixels Specifies the width of the canvas. Default value is 300

Global Attributes

The <canvas> tag also supports the Global Attributes in HTML.

Event Attributes

The <canvas> tag also supports the Event Attributes in HTML.

Browser Support

Element Chrome IE Firefox Safari Opera
<canvas> 4.0 9.0 2.0 3.1 9.0

Default CSS Settings

Most browsers will display the <canvas> element with the following default CSS settings:

canvas {
  height: 150px;
  width: 300px;
}

Conclusion

The <canvas> element is a versatile and powerful tool for creating dynamic visual content on web pages.


By understanding its attributes and how to manipulate them with JavaScript, developers can create engaging and interactive graphics that enhance the user experience.