Pan and Scale in the Same Operation

To pan and scale in the same operation, we simply need to pan using the same window and window properties as Example 4-14 and the same source scale factor as Example 4-15:

var windowX=1580;
var windowY=1190;

In the drawScreen() function, we will use this to draw the image:

context.drawImage(photo, windowX, windowY,windowWidth*2,windowHeight*2,
                  0,0,viewPortWidth,viewPortHeight);

Example 4-15 shows this powerful combination in action.

Example 4-15. Scale and pan to a spot on the image

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


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

var windowX=1580;
var windowY=1190;


function eventPhotoLoaded() {
    drawScreen();
}

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

When Example 4-15 is run, you will see that we have panned to a new spot on the large image and doubled the size of the image source rectangle. This acts as a zoom-out feature, and the butterfly becomes much clearer than in Example 4-14. Figure 4-16 shows this example in action.

Pan and scale applied to the butterfly image

Figure 4-16. Pan and scale applied to the butterfly image

Next we take a look at manipulating individual pixels on the canvas.

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.