Friday, September 12, 2008

HTML Canvas Element - Part 3

This is Part 3 of the HTML Canvas Tutorial. If you haven't already you should read Part 1 and Part 2.

In this section we will create a key press listener and zoom our triangle in when we press 'z' and out when we press 'x'.

To do this we add a onKeyUp event to the body tag, and a corresponding handleKeyUp javascript function:

function handleKeyUp(evt) {
var e = evt ? evt : event;
if (e.keyCode == 90) {
scale+=.1;
} else if(e.keyCode == 88) {
scale-=.1;
}
draw();
}


<body onload="draw();" onkeyup="handleKeyUp(event);">
<canvas id="canvas" width="150" height="150"></canvas>
</body>


The variable scale is defined as a global javascript variable and we'll use it to call 'ctx.scale(x,y)'

Before we do that though we'll have to call clearRect(x,y,width,height) to clear the image and redraw. The entire script is displayed below:

<html>
<head>
<script type="application/x-javascript">

var scale=1;
function draw() {
// Get Reference to the 'canvas' tag
var canvas = document.getElementById("canvas");
if (canvas.getContext){
// Get a context that allows us to draw on.
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.scale(scale,scale);

// Move cursor and draw the outline of the Triangle
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(50,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);

// Actually Draw, you could call stroke instead which will draw the outline
ctx.fill();
ctx.restore();

}

}
function handleKeyUp(evt) {
var e = evt ? evt : event;
if (e.keyCode == 90) {
scale+=.1;
} else if(e.keyCode == 88) {
scale-=.1;
}
draw();
}


</script>
</head>
<body onload="draw();" onkeyup="handleKeyUp(event);">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>


That's it! I hope that got you interested in the Canvas element. If you have any questions leave a comment and I would be glad to answer them.

For more information I recommend the following sites:
http://developer.mozilla.org/en/Canvas_tutorial
http://en.wikipedia.org/wiki/Canvas_(HTML_element)
http://blog.vlad1.com/2008/06/04/html-canvas-in-firefox-3/

No comments: