Changing the Image Source Scale
Aside from using the viewport settings to scale an image when drawn to the
canvas, we can also change the source height and width vales to display
the image in a new scale. We will keep the view port height and width
the same, but change the window height and window width values. When we
make these greater than the size of the actual window, we will see more
of the image in the 500×500 canvas, and the details will appear to be a
little clearer. To scale an image, we need to change the final width
and height
values of the drawImage()
function. Let’s examine how we
would scale to 2x of the original size of the image while panning at the
same time. The drawImage()
function will look like this:
context
.
drawImage
(
photo
,
windowX
,
windowY
,
windowWidth
*
2
,
windowHeight
*
2
,
0
,
0
,
viewPortWidth
,
viewPortHeight
);
Example 4-13 modifies Example 4-12 and adds in the
*2
to windowHeight
and windowWidth
for zooming out (2x zoom out) from
the original image.
Example 4-13. Scale with source properties
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
=
0
;
var
windowY
=
0
;
function
eventPhotoLoaded
()
{
drawScreen
()
}
function
drawScreen
(){
context
.
drawImage
(
photo
,
windowX
,
windowY
,
windowWidth
*
2
,
windowHeight
*
2
,
0
,
0
,
viewPortWidth
,
viewPortHeight
);
}
If you compare the output from Examples 4-12 and 4-13, you will notice that ...
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.