HTML and CSS Reference
In-Depth Information
Follow these steps:
1. Open the advert.html file in your text editor.
2. Create a <canvas> element above the <script> element that is 600 pixels wide and 150 pixels high.
Give this element the ID adCanvas .
<canvas id="adCanvas" width="600" height="150"></canvas>
<script src="adscript.js"></script>
3. Download the fallback.png file from the book's website and place it in your
canvas-ad folder. You can find this file in folder 2.
4. Create a new <img> element within the <canvas> element for the fallback image.
<canvas id="adCanvas" width="600" height="150">
<img src="fallback.png" alt="Joe's Pizza Co. Advert"
width="600" height="150">
</canvas>
5. Save the advert.html file.
That covers all the HTML code that you will be writing in this chapter. Now you need to get a reference to the can-
vas in your JavaScript code, using the following steps.
The code in this exercise can be found in folder 3.
1. Open the adscript.js file in your text editor.
2. Within the empty function block that you created earlier, create a new variable called adCanvas and ini-
tialize it by fetching the canvas from your HTML.
window.onload = function() {
var adCanvas = document.getElementById(“adCanvas");
}
3. Now you need to check to see if the user's browser supports the Canvas API. Do this by creating an if
statement that checks to see whether your new adCanvas variable has a getContext method. This is
similar to how you checked for geolocation support in Chapter 13.
window.onload = function() {
var adCanvas = document.getElementById(“adCanvas");
if (adCanvas.getContext) {
}
}
4. Finally, you need to get a 2D drawing context. You will use this to draw onto the canvas. Create a new vari-
able called ctx and initialize it by calling getContext(“2d”) on your adCanvas variable. The d
Search WWH ::




Custom Search