Alright what IS this Canvas thing anyways? The Web Hypertext Application Technology Working Group says this:
canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.”
The Canvas element has two only attributes – width and height and when not specified they take up the default values of 300 and 150 respectively. Below is what my HTML file looks like:
In case you’re wondering, this is not a MVC or any kind of web application. This is plain ol’ HTML even though I’m writing all this in VS 2010.
This is what my page renders as:
Now let’s get to our CustomScript.js file.
The script only looks long and complicated, but is not. I’ll go over the main steps.
Get a ‘hold’ of your canvas object and retrieve the ‘2d’ context out of it. On mousemove event, write the current x and y coordinates to the ‘currentPosition’ element. On mouseup event, check if this is the first time the user has clicked on the canvas. The coloring of the canvas is done in the fillBackground() function.
We first need to start a new path. This is done by calling the beginPath() function on our context. The moveTo() function sets the starting point of our path. The lineTo() function sets the end point of the line to be drawn. The stroke() function is the one that actually draws the line on our canvas.
So if you want to play with the demo, here’s how you do it. First click on the canvas (nothing visible happens on the canvas). The second click draws a line from the first click to the current coordinates and so on and so forth.
Click on the ‘Clear’ button, to reset the canvas and to give your creativity a clean slate. Here’s a sample output:
Verdict: HTML5 and IE9 – I think we’re on to something big and great here!