HTML and CSS Reference
In-Depth Information
There is one caveat when drawing images onto a canvas. The JavaScript code that you write to draw onto your can-
vas will likely execute before your image has finished loading. If you call the drawImage() function when the im-
age is still loading, nothing will happen, and so your image won't appear on your canvas. To get around this, you
need to attach a function to the onload event of your Image object and call the drawImage() function from
there. Here is an example:
var img = new Image();
img.onload = function() {
ctx.drawImage(img,0,0);
}
img.src = “myImage.png";
For your advertisement, you need the image to be drawn first so that all the other objects appear above it on the can-
vas. However, as I mention earlier, the JavaScript code that you previously wrote that draws the objects on the can-
vas will execute before the image has loaded, causing the image to be drawn on top of everything else, not below it.
You need some way of telling the browser to only start drawing on your canvas after the image has loaded. Well, you
just learned how to do this by attaching a function to the onload event of your Image object. Now you just need a
way of calling the rest of your drawing code once the image has been drawn. Lucky that you put all your drawing
code into that drawAdvert() function then, isn't it?
You could just copy all your drawing code inside the event listener, but using a function makes it much easier to
manage your code in the long run.
Add the background image to your canvas with the following steps:
The code in this exercise can be found in folder 12.
1. Open the adscript.js file in your text editor.
2. Download the background.png file from the book's website and place it in your canvas-ad folder.
You can find this image in folder 12.
3. Go to the top of the adscript.js file and delete the call to the drawAdvert() function that is below
where you initialize the ctx variable.
if (adCanvas.getContext) {
// Initialize a 2d drawing context.
var ctx = adCanvas.getContext(“2d");
drawAdvert();
}
4. In its place, create a new variable called img and initialize it by creating a new empty Image object.
Search WWH ::




Custom Search