What is actually Canvas tag in HTML5?
<canvas> tag was added in HTML5 as an element that allows the browser / client to draw shapes and images without any plugin. The canvas tag is used to draw graphics on a rectangular area inside a web page by using JavaScript. The canvas tag can be used to draw graphs, generate photo compositions and dynamic content like animations, games etc.Using only JavaScript you can create pieces of code that will do the painting in the canvas.
Declare a <canvas> tag
To declare a canvas tag you simply add it as a normal HTML tag
<canvas id=”mycanvas” width=”400″ height=”300″>Your browser does not support HTML5</canvas>
As you can see <canvas> has normal properties :
- id – the id identifier in DOM structure. Later you will see that it is used to access canvas element
- width – the width of the canvas
- height – the height of the canvas
Fall back option
Your browser might not support <canvas> so at least you can provide your users a clue about that. To do that you can add text or images inside the <canvas> tag.In our example we have a message “Your browser does not support HTML5” that will warn user about this issue.Another option would be to display a static image (JPG or GIF) with a mockup of how the canvas will look if it will work.
Obtain context
To be able to actually use the <canvas> engine you have to access it. In order to do that you have to use JavaScript to get access the <canvas> element and once you grab it you can access its “2d” context.
To access the <canvas> element is a standard document.getElementById call:
var eMyCanvas = document.getElementById(‘mycanvas’);
Once you have it you need access to its context. As canvas will, in near future, have also a 3D engine you have to pick what engine to use. We need “2D” engine.
var ctx = eMyCanvas.getContext(‘2d’);
Example code:
<html>
<body>
<canvas id=”demoCanvas” width=”380″ height=”180″></canvas>
<script type=”text/javascript”>
var can = document.getElementById(“demoCanvas”),
context = can.getContext(“2d”);
context.fillStyle = ‘blue’;
context.fillRect(10, 20, 200, 100);
</script>
</body>
</html>