Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Drawing by using the element CHAPTER 12 491


var img = new Image();
img.src = “images/IceBoat.jpg";
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
}

The results are shown in Figure 12-20. The image is drawn at its native width and height. If
the image is larger than the canvas, it’s clipped. This image is 538 pixels wide and 718 pixels
tall. Because the canvas is 800 pixels wide and 600 pixels tall, the bottom of this image is
clipped.

FIGURE 12-20 he drawn image placed in the upper-left corner of the canvasT

You might need to control the size of the drawn image. Specify this with two more argu-
ments when calling the drawImage method, the width and the height. In the following
example, the width is set to 300, and the height is set to 400.
function drawImage() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');
var img = new Image();
img.src = “images/IceBoat.jpg";
img.onload = function () {
Free download pdf