HTML5 getting started with canvas

HTML5 and javascript are the next wave of web capabilities to do rich content without flash or any other plug-ins like unity. A big part of this is the canvas element which allows you to draw and manipulate content in 2D and in some browsers 3D with webGL. The canvas tag looks like the following:

<canvas id="myCanvas">your browser does not support canvas</canvas>

Pretty basic right?
So to actually make things appear we need to reference this with javascript and then draw whatever we want.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

Now we have the canvas and the context which is where we'll actually do the rendering, notice we specified 2d, if we're doing 3d drawing we would specify a different context to draw in. So now we can draw.

ctx.fillRect(10, 10, 100, 50);

If you are familiar with Flash's Drawing API this will look familiar. The properties look like this fillRect(x, y, width, height). You can reference the full canvas API here. You can also draw any HTML element like images or videos with the below method.

var myImageElement = new Image();
myImageElement.src = "images/image.png";
ctx.drawImage(myImageElement, 10, 10);

What we're doing is creating an image element in javascript and then drawing it onto the canvas. Once you can do this we can start to unravel the true potential of canvas by animating it.

var newX = 10;
setInterval("loop()", 100);

function loop(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(myImageElement, newX, 10);

So now that we have animation we can do all sorts of magic! Using javascript you can capture events to change behavior for rich interactive experiences.