In this article I describe the <canvas> tag in HTML5.
<canvas> tag
The <canvas> tag displays data and/or images on a browser. The HTML5 canvas element uses JavaScript to draw graphics on a web page. A canvas is a rectangular area and you can control every pixel of it. It can be used for rendering graphs, game graphics and other visual images. The <canvas> tag was introduced in HTML5.
To draw on the canvas, the canvas tag is used in conjunction with the getContext(Context Id) method.
Any context between the <canvas></canvas> tags is "fallback content"-meaning it will be displayed only if the canvas cannot be displayed .The context can be 2d or 3d.
Each canvas element can only have one context. If we use the getcontext() method multiple times, it will return a reference to the same context object.
Browser Support
Browsers that support the canvas element are Internet Explorer, Mozilla Firefox, Safari and Opera, as shown in the following:
Internet Explorer |
Firefox |
Safari(Desktop) |
Chrome |
Opera(Desktop) |
Safari(Mobile) |
Opera(Mobile) |
Android Browser |
6.0 |
2.0 - 6.0 |
3.1- 3.2 |
4.0-13.0 |
9.0-11.0 |
3.2 |
10.0 |
2.0 |
7.0 |
7.0 |
4.0 |
14.0 |
11.1 |
4.0 |
11.0 |
2.1 |
8.0 |
8.0 |
5.0 |
15.0 |
11.5 |
4.2-4.3 |
11.1 |
2.3,3.0 |
9.0 |
9.0 |
5.1 |
16.0 |
11.6 |
5.0 |
11.5 |
4.0 |
28.77% |
19.70% |
6.77% |
30.01% |
1.42% |
2.79% |
2.32% |
3.02% |
Example
The following code creates a canvas element in a HTML page:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas">Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ct = c.getContext('2d');
ct.fillStyle = 'Red';
ct.fillRect(0, 0, 180, 220);
ct.fillStyle = 'Purple';
ct.fillRect(30, 30, 100, 110);
ct.fillStyle = 'yellow';
ct.fillRect(60, 60, 50, 55);
ct.fillStyle = 'green';
ct.fillRect(8, 8, 10, 15);
ct.fillStyle = 'Pink';
ct.fillRect(164, 8, 10, 15);
ct.beginPath();
ct.moveTo(0, 10);
ct.lineTo(180, 10);
ct.strokeStyle = "Blue";
ct.stroke();
ct.moveTo(10, 0);
ct.lineTo(10, 220);
ct.strokeStyle = "Blue";
ct.stroke();
ct.moveTo(170, 0);
ct.lineTo(170, 210);
ct.strokeStyle = "Blue";
ct.stroke();
ct.font = "bold 12px arial";
ct.fillText("HTML5", 70, 50);
</script>
</body>
</html>
Output