HTML and CSS Reference
In-Depth Information
Figure 4-3. Resizing an image as it is drawn
In Example 4-2 , we have added a gray box so we can better see the placement of the
images on the canvas. The image we placed on the screen can scale in size as it is painted,
saving us the calculation and steps necessary to use a matrix transformation on the
object. The only caveat is that the scale origin point of reference is the top-left corner
of the object. If we used a matrix operation, we could translate the origin point to the
center of the object before applying the scale.
We have placed two 32×32 objects on the canvas to show that these two function calls
are identical:
context.drawImage(spaceShip, 0, 0);
context.drawImage(spaceShip, 0, 34,32,32);
Aside from the fact that the second is placed 34 pixels below the first, the extra 32,32
at the end of the second call is unnecessary because it is the original size of the object.
This demonstrates that the scale operation does not translate (or move) the object on
any axis. The top-left corner of each is 0,0.
Copying Part of an Image to the Canvas
The third set of parameters that can be passed into drawImage() allows us to copy an
arbitrary rectangle of data from a source image and place it onto the canvas. This image
data can be resized as it is placed.
We are going to use a second source image for this set of operations: spaceships that
have been laid out on what is called a tile sheet (also known as a sprite sheet , a texture
sheet , or by many other names). This type of file layout refers to an image file that is
broken up physically into rectangles of data. Usually these rectangles have an equal
width and height. The “tiles” or “sprites” we will be using are 32 pixels wide by 32
pixels high, commonly referred to as 32×32 tiles.
Search WWH ::

Custom Search