HTML and CSS Reference
In-Depth Information
var adWidth = 300;
var adHeight = 250;
canvas.width = adWidth;
canvas.height = adHeight;
context.moveTo(0,0);
context.lineTo(adWidth,0);
context.moveTo(adWidth,0);
context.lineTo(adWidth,adHeight);
context.moveTo(adWidth,adHeight);
context.lineTo(0,adHeight);
context.moveTo(0,adHeight);
context.lineTo(0,0);
context.stroke();
</script>
</html>
This code outlines a dynamic way to add a border to advertisements. Start off by getting a reference to the
canvas element and call it canvas . Next, set a 2D drawing context and declare two variables, adWidth and adHeight .
These values will dynamically update the canvas element to the desired dimensions. This example makes use of the
common ad size 300 × 250. Finally, use the drawing API of canvas to move and add a line around the whole element
by using the sequence of methods lineTo and moveTo , which render the image in Figure 4-2 .
1px
Figure 4-2. Creating a 300 × 250 border using the canvas element
As you see, drawing a dynamic ad border using the canvas element is fairly simple. (This can be really helpful,
as publisher and IAB specs require you to add a 1-pixel border around advertisements.) It doesn't end there, though.
Play around a bit with lines to see what else you can come up with. Keep in mind that anything you can do with your
design tools, you can pretty much do using canvas , even adding Bézier curves and arcs. If you need a jumping-off
point, start at the W3C schools “try it” editor ( w3schools.com/html5/tryit.asp?filename=tryhtml5_canvas_line ) .
Shapes
If you can create lines, you can create shapes (no shocker here!). Let's take a look at creating complex shapes using
canvas . Having successfully rendered a green square to the screen, let's make a star shape (see Listing 4-5). To save on
space from here on, I will omit the full HTML markup and focus on the JavaScript portions.
 
Search WWH ::




Custom Search