One of the most talked about features of the upcoming HTML5 code is the <canvas> element / tag, some of you may be aware that the <canvas> was first developed by Apple for use in their Mac OS X Dashboard and also implemented at a later date by the Safari browser, Most Gecko based browsers such as FireFox have current support for the <canvas> tag.

We will keep this example very basic and over time we will delve in a little deeper, our example below should give you a rough idea of what is possible with this new inclusion. See the example here: HTML5 Canvas Test

HTML5 Canvas Test Code:

<html>
<head>
<title>Canvas tutorial</title>
<script type=”text/javascript”>
function draw(){
var canvas = document.getElementById(‘tutorial’);
if (canvas.getContext){
var ctx = canvas.getContext(‘2d’);
}
}
</script>
<style type=”text/css”>
canvas { border: 2px solid red; }
</style>
</head>
<body onLoad=”draw();”>
<canvas id=”tutorial” width=”175″ height=”175″></canvas>
</body>
</html>

As you can see the “Draw” function in this script tells the browser what to render, as our example shows above we have told the browser to “Draw” once the page has finished loading this is controlled by the “onLoad” function, there are many variables you can use for this.

Here is another quick example that tells the browser to draw 2 rectangles which overlay each other, HTML5 Canvas Test #2

HTML5 Canvas Test #2 Code:

<html>
<head>
<script type=”application/x-javascript”>
function draw() {
var canvas = document.getElementById(“canvas”);
if (canvas.getContext) {
var ctx = canvas.getContext(“2d”);

ctx.fillStyle = “rgb(40,0,0)”;
ctx.fillRect (20, 20, 65, 60);

ctx.fillStyle = “rgba(0, 0, 160, 0.5)”;
ctx.fillRect (40, 40, 65, 60);
}
}
</script>
</head>
<body onLoad=”draw();”>
<canvas id=”canvas” width=”150″ height=”150″></canvas>
</body>
</html>

While it may seem very simple the new JavaScript & <canvas> element are going to play a huge part in the way we develop websites and applications in the future, the options are endless. As mentioned on our site several other times, over the coming weeks and months we will take a look into much more advanced HTML5 tutorials. Please feel free to copy the above code and have a play around with it on your own computer.

share save 256 24 Canvas examples