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.

Figure 4-13. An image in a small logical window
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.