HTML5 - Canvas
What is HTML5 Canvas
The HTML5 element <canvas> allows to draw graphics using JavaScript. It is used to draw graphs, make photo compositions or do easy (and not so easy) animations.
Here is a simple <canvas> element that has only two specific attributes width and height plus all the core HTML5 attributes like id, name, and class, etc.
The code below is a simple <canvas> element that posseses only two specific attributes width and height including all the main HTML5 attributes like id, name, and class, etc.
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
You can find that <canvas> element in the browser Document Object Model(DOM) using the getElementById() method like so:
var canvas = document.getElementById("mycanvas");
Below is a simple example that shows how to use the <canvas> element in HTML5 document.
<!DOCTYPE HTML> <html> <head> <style>
#canvas {
border:1px solid red;
}
</style> </head> <body> <canvas id = "canvas" width = "100" height = "100"></canvas> </body> </html>
The Rendering Context
The HTML5 <canvas> is blank initially, and in other to display something, the script for it has to first access the rendering context and draw on it.
The HTML5 <canvas> posses a DOM method that is getContext that is used to get the rendering context and all of it's drawing functions. This particular takes in just one parament with is the type of the context.
The code below is meant to get the required context along with a check to see if your browser supports the <canvas> element:
var canvas = document.getElementById("mycanvas"); if (canvas.getContext) { var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here }
Browser Support
The newest versions of Firefox, Safari, Chrome, and Opera all posses support for the HTML5 Canvas element but Internet Explorer 8 does not have support for the element natively.
Although, you can make use of ExplorerCanvas to get canvas support on the Internet Explorer. You just need to include this JavaScript code:
<!--[if IE]><script src = "excanvas.js"></script><![endif]-->