Game Development Reference
In-Depth Information
Now imagine I told you to do the same thing on the dry erase board. You might pause for a minute but you'd
ultimately come to only one solution. You would need to erase it, and then draw it again at its new desired position.
This is precisely how Canvas works. It's not enough to manage and update the next position of every sprite in your
game; you need to manually erase and redraw them as well. These visual graphics are not collectively retainable,
but are simply pixels painted on to the canvas with no other reference to what they are or represent.
To demonstrate how this looks in action, let's look at a simple example of how you would do this in JavaScript
using the Canvas API (see Listing 1-1). The result is demonstrated in Figure 1-2 .
Listing 1-1. Drawing and Moving Graphics with the Canvas API
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var butterfly = new Image();
butterfly.src = "images/butterfly.png";
butterfly.onload = drawButterflies;
function drawButterflies() {
ctx.drawImage(butterfly, 0, 0, 200, 138, 0, 0, 200, 138);
ctx.drawImage(butterfly, 0, 0, 200, 138, 200, 0, 200, 138);
ctx.drawImage(butterfly, 0, 0, 200, 138, 400, 0, 200, 138);
setTimeout(moveButterfly,1000);
}
function moveButterfly(){
ctx.clearRect(0,0, canvas.width,canvas.height);
ctx.drawImage(butterfly, 0, 0, 200, 138, 0, 0, 200, 138);
ctx.drawImage(butterfly, 0, 0, 200, 138, 200, 200, 200, 138);
ctx.drawImage(butterfly, 0, 0, 200, 138, 400, 0, 200, 138);
}
Figure 1-2. Bitmaps drawn onto the canvas using the Canvas API
Search WWH ::




Custom Search