HTML and CSS Reference
In-Depth Information
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 ( spaceShip , 0 , 0 );
placeShip ( spaceShip , 50 , 50 );
function placeShip ( obj , posX , posY , width , height ) {
iif ( width && height ) {
context . drawImage ( obj , posX , posY , width , height );
} else
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.
The website for this topic contains only the files necessary to complete the examples. We have mod-
ified Ari's files to fit the needs of this topic.
Figure 4-2 shows two copies of the image painted to the canvas. One of the copies has the
top-left starting location of 0,0, and the other starts at 50,50.
Search WWH ::

Custom Search