Changing the ViewPort Property of the Image

We can change the ViewPort property of the drawn image by modifying the viewPortWidth and viewPortHeight values. Example 4-12 shows the image drawn into a 200×200 window, using the same pixels as the 400×400 copy from Example 4-11. Essentially, this scales the image copy down to fit in a smaller space but uses the same source pixels:

var viewPortWidth=200;
var viewPortHeight=200;

Example 4-12 contains these simple changes.

Example 4-12. Changing scale with ViewPort properties

var photo=new Image();
photo.addEventListener('load', eventPhotoLoaded , false);
photo.src="butterfly.jpg";


var windowWidth=500;
var windowHeight=500;
var viewPortWidth=200;
var viewPortHeight=200;

var windowX=0;
var windowY=0;


function eventPhotoLoaded() {
    drawScreen()
}

function drawScreen(){
        context.drawImage(photo, windowX, windowY,windowWidth,windowHeight,
                          0,0,viewPortWidth,viewPortHeight);
}

When you test Example 4-12, you will see the exact same portion of the image copied into a smaller part of the canvas. Figure 4-13 shows an example of this scaled viewport window.

An image in a small logical window

Figure 4-13. An image in a small logical window

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.