Canvas Element in HTML5

Introduction

 
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. 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 an HTML page:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>   
  4. <canvas id="myCanvas">Your browser does not support the HTML5 canvas tag.</canvas>   
  5. <script>  
  6.     var c = document.getElementById("myCanvas");  
  7.     var cct = c.getContext('2d');  
  8.     ct.fillStyle = 'Red';  
  9.     ct.fillRect(0, 0, 180, 220);  
  10.     ct.fillStyle = 'Purple';  
  11.     ct.fillRect(30, 30, 100, 110);  
  12.     ct.fillStyle = 'yellow';  
  13.     ct.fillRect(60, 60, 50, 55);  
  14.     ct.fillStyle = 'green';  
  15.     ct.fillRect(8, 8, 10, 15);  
  16.     ct.fillStyle = 'Pink';  
  17.     ct.fillRect(164, 8, 10, 15);  
  18.     ct.beginPath();  
  19.     ct.moveTo(0, 10);  
  20.     ct.lineTo(180, 10);  
  21.     ct.strokeStyle = "Blue";  
  22.     ct.stroke();  
  23.     ct.moveTo(10, 0);  
  24.     ct.lineTo(10, 220);  
  25.     ct.strokeStyle = "Blue";  
  26.     ct.stroke();  
  27.     ct.moveTo(170, 0);  
  28.     ct.lineTo(170, 210);  
  29.     ct.strokeStyle = "Blue";  
  30.     ct.stroke();  
  31.     ct.font = "bold 12px arial";  
  32.     ct.fillText("HTML5", 70, 50);  
  33. </script>  
  34. </body>  
  35. </html> 
Output
 
canvas1.html.jpg