HTML <canvas> tag

Use of <canvas> tag

The <canvas> tag is new in HTML5. It is used to draw graphics, creating animations etc. of arbitrary size coding with JavaScript usually. It is somewhat like <img> tag with the exception that the img tag needs to import an image from another directory or source while the <canvas> tag draws within the page using JavaScript languuage.
Always Specify an id Attribute, a width and height attribute to define size of the canvas. To add a border use style attribute.
If your browser does not support HTML <canvas> elements, the texts within the <canvas> tag and </canvas> tag will be seen. Although HTML <canvas> tag is used in drawing graphics, the act is performed by JavaScript.
We have to use <script> tag to import JS language within the document.

Basic Needs of HTML5 canvas

1. A <canvas> tag in HTML to place the drawing canvas.
2. Javascript to do the drawing (may be line, box, circle, texts etc).


Example of <canvas> tag

<canvas id = "circle" width = "280" height = "150" style = "border:1px solid red"> Your browser does not support canvas element. </canvas>
<script>
var c = document.getElementById("circle");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(140, 60, 50, 0, 2 * Math.PI);
ctx.stroke();
</script>

Result will look like this

Your browser does not support canvas element.

Supported Browsers

The following versions are the minimum versions that support the <canvas> tag fully.

Tag Chrome browser Internet explorer browser Firefox browser Safari browser Opera browser
<canvas> 4.0 9.0 2.0 3.1 9.0

Full Code Example

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id = "rectangle" width = "250" height = "190" style = "border:1px solid red;"> This sentence will be displayed when your browsers does not support it. </canvas>
<script>
var c = document.getElementById("rectangle");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(20, 40, 150, 100);
ctx.fillStyle = "red";
ctx.fill();
</script>
</p>
</body>
</html>

Output

This sentence will be displayed when your browsers does not support it.

Attributes of <canvas> tag

Attribute Value Notes
height pixels It defines the height of the canvas.
Default value is 150px.
width pixels It defines the width of the canvas.
Default value is 300px.