Canvas in HTML 5


As you well know HTML5 has some new elements including the Canvas element. A Canvas is an object that displays graphics in it.
But for a drawing process, we'll need to use JavaScript. You can draw anything you want: arcs, shapes, images, text and much more.
In our example, we'll be drawing a shape.
Since HTML5 is platform-independent, you can display these codes on any system.
You don't actually need First-Class Web Editors for building HTML5 sites; you just need an HTML5-supported Web Browser and a NotePad application.
Alright then let's start. First, open a new NotePad application. And write the following code:
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title>Canvas in HTML 5</title>  
  5.         <script type="text/javascript">  
  6.     function load_canvas() {  
  7.     }  
  8. </script>  
  9.     </head>  
  10.     <body onload="load_canvas()">  
  11.         <h1>Canvas Example</h1>  
  12.         <canvas id="cnv1" width="500" height="500"></canvas>  
  13.     </body>  
  14. </html>  
What we have added here is a Javascript function that will run after page loaded.
And then we have added a canvas element with an id, width, and height.
These parameters are needed while using a canvas.
So let's keep going. Create 2 variables inside the load_canvas function now:
  1. var canvas = document.getElementById('cnv1');  
  2. var canvascanvas1 = canvas.getContext('2d');  
We'll be using these variables to access canvas elements from Javascript calls. As you can see above we have accessed the cnv1 object which we have set the "id" value in the Canvas element.
Now add these codes after the codes above:
  1. canvas1.fillStyle = "rgba(100, 200, 0, 1)";  
  2. canvas1.fillRect(30, 30, 75, 70);  
Here we are creating a Rectangle object and filling it with color as we have set it with rgba. These codes will display a rectangle with a given width, height, x, y and rgba values in your canvas.
Full Code:
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title>Canvas in HTML 5</title>  
  5.         <script type="text/javascript">  
  6.     function load_canvas() {  
  7.         var canvas = document.getElementById('cnv1');  
  8.         var canvas1 = canvas.getContext('2d');  
  9.         canvas1.fillStyle = "rgba(100, 200, 0, 1)";  
  10.         canvas1.fillRect(30, 30, 75, 70);  
  11.     }  
  12. </script>  
  13.     </head>  
  14.     <body onload="load_canvas()">  
  15.         <h1>Canvas Example</h1>  
  16.         <canvas id="cnv1" width="500" height="500"></canvas>  
  17.     </body>  
  18. </html>  
Now save it as .html and view it in an HTML5 Supported Web Browser.
You'll get a similar view:
But before that if you are using IE9 just like me, you'll be receiving this message before it can run:
You'll need to Allow Blocked Content.
We'll be talking more about Canvas in the following articles.

Similar Articles