HTML and CSS Reference
In-Depth Information
function eventShipLoaded() {
function drawScreen() {
context.drawImage(spaceShip, 0, 0);
context.drawImage(spaceShip, 50, 50);
Figure 4-1 shows the 32×32 ship1.png file.
Figure 4-1. Load and display an image file
In practice, we would probably not put all of our drawing code directly into a function
such as drawScreen() . It almost always makes more sense to create a separate function,
such as placeShip() , shown here:
function drawScreen() {
placeShip(context, spaceShip, 0, 0);
placeShip(context, spaceShip, 50, 50);
function placeShip(ctx, obj, posX, posY, width, height) {
if (width && height) {
context.drawImage(obj, posX, posY, width, height);
} else {
context.drawImage(obj, posX, posY);
The placeShip() function accepts the context, the image object, the x and y positions,
and a height and width. If a height and width are passed in, the first version of the
drawScreen() function is called. If not, the second version is called. We will look at
resizing images as they are drawn in the next section.
The ship1.png file we are using is a 32×32 pixel .png bitmap, which we have modified
from Ari Feldman's excellent SpriteLib. SpriteLib is a free library of pixel-based game
sprites that Ari has made available for use in games and topics. You can find the entire
SpriteLib here: .
Search WWH ::

Custom Search