The canvas element is used to draw graphics on a web page. The HTML5 canvas element uses JavaScript to draw graphics on a web page; hence the programmer should possess some knowledge of JAVA script as well. The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images. To add a canvas element to the HTML5 page, specify the id, width, and height of the element:
1 |
<canvas id="myCanvas" width="200" height="100"></canvas> |
The canvas element has no drawing abilities of its own. All drawing must be done inside a JavaScript. For example, consider the code:
1 2 3 4 5 6 |
<script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); cxt.fillStyle="#FF0000"; cxt.fillRect(0,0,150,75); </script> |
In the above code, JavaScript uses the id to find the canvas element. This is done in the following line from the above code:
1 |
var c=document.getElementById("myCanvas"); |
After finding the ID, context object is created. This is done in the following line:
1 |
var cxt=c.getContext("2d"); |
The getContext(“2d”) object is a built-in HTML5 object, with many methods to draw paths, boxes, circles, characters, images and more.
Next, we consider a simple example of drawing a gradient background with the colors of your choice. This is an important feature in the canvas elements yet is quite easy to undertake. Consider the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); var grd=cxt.createLinearGradient(0,0,175,50); grd.addColorStop(0,"#FF0000"); grd.addColorStop(1,"#00FF00"); cxt.fillStyle=grd; cxt.fillRect(0,0,175,50); </script> </body> </html> |
The code first checks whether the browser supports the canvas element or not. If it does, the code proceeds further and get the ID of the canvas element and create the context element of the gradient. Colors and style is then specified as needed. Canvas creation is an important and innovative concept of HTML5 and has considerably increased the power of web programming.