Resizing an Image Painted to the Canvas

To paint and scale drawn images, we can also pass parameters into the drawImage() function. For example, this second version of drawImage() takes in an extra two parameters:

drawImage(Image, dx, dy, dw, dh)

dw and dh represent the width and height of the rectangle portion of the canvas where our source image will be painted. If we want to scale the image to only 64×64 or 16×16, we would use the following code:

context.drawImage(spaceShip, 0, 0,64,64);
context.drawImage(spaceShip, 0, 0,16,16);

Example 4-2 draws various sizes to the canvas.

Example 4-2. Resizing an image as it is drawn

function eventSheetLoaded() {
   drawScreen();
}

function drawScreen() {

   context.drawImage(spaceShip, 0, 0);
   context.drawImage(spaceShip, 0, 34,32,32);
   context.drawImage(spaceShip, 0, 68,64,64);
   context.drawImage(spaceShip, 0, 140,16,16);
}

See Figure 4-3 for the output to this example.

Resizing an image as it is drawn

Figure 4-3. Resizing an image as it is drawn

In Example 4-2, we have added a gray box so that 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 ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.