We need to learn more about HTML 5 (wikipedia link) and, specifically the <canvas> tag for a new project we're starting on.
The Canvas tag allows for drawing of 2-dimensional vector shapes on a page without requiring any plug ins. Sounds great, but a few things immediately pop out:
- <canvas> isn't supported in all browsers (Internet Explorer, namely, which won't support <canvas> until, apparantly IE9)
- HTML 5 is not expected to become a standard until at least 2012.
- In it's original inception, HTML 5 would support a variety of media elements including video and audio. This has now been removed from the standard due to conflicts with licensing from various vendors.
...that there is no suitable codec that all vendors are willing to implement and ship.
(via whatwg)
Even still, we need to be forward-looking and start thinking of the future of web, so we're diving into the <canvas> tag.
Here's a basic implementation:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
<!--
function drawIt() {
var canvas = document.getElementById('sqCanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 50, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 80, 80);
} else {
alert('Canvas tag not supported.');
}
}
//-->
</script>
</head>
<body>
<canvas id="sqCanvas" width="200" height="200"></canvas>
<p><input type="button" value="Draw" onClick="drawIt();"/></p>
</body>
</html>
This gives a webpage that looks like this:

So, pretty simply:
- Define the <canvas> tag with an id and height and width:
<canvas id="theCanvas" width="200" height="200"></canvas> - Get the 2d context of the element:
var canvas = document.getElementById('theCanvas');
var ctx = canvas.getContext('2d'); - Draw your shape:
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 50, 50);
Few things to note on this:
- If you want to set this up to render in IE, either wait for IE9 or use ExplorerCanvas as an override for the time being.
- Firefox expects a closing </canvas> tag, so you can't do the <canvas /> trick. Not sure if other browsers also require this, but it's safe to put in either way.
- You can style a canvas tag along with the rest of the document:

- Note that Firefox has a slight quirk that I wasn't expecting. Initially I styled the height and width through CSS and got this instead, which ended up being a stretch instead of an element size definition. This is why the width/height are defined in the tag itself.

Lots more information on <canavs> from here and here.