HTML and CSS Reference
In-Depth Information
Figure 4-1. A 250 × 250 square made with the canvas element
If you see the square, you're ready to review what's going on. If you don't, be sure you're using a modern browser,
one that supports canvas , and double-check your code.
Check for canvas support at .
First, let's create a variable that gets a reference to the canvas element in the DOM. In this case, give it the ID
adCanvas ” by writing <canvas id="adCanvas" width="300" height="250"></canvas> in the markup. Once that
reference is there, add a 2D context to the canvas so canvas knows how to paint graphics. In short, the 2D context
represents a flat Cartesian coordinate system where the origin (0,0) is at the top left corner of the canvas , with x values
increasing when going right and y values increasing when going down—similar to what you may have learned in algebra.
Having gotten this element and context, let's start “painting” on the canvas . To do so, tell the fillStyle property
to render in green (it can also take a hex and RGB value), and then call the method fillRect to render a rectangle
by passing in specific parameters or arguments by writing context.fillRect(0, 0, 250, 250); . In Figure 4-1 , a
square was created by passing in 0 for its x-coordinate, 0 for its y-coordinate, and 250 for both its width and height.
This value takes a floating-point number; that is, not having it paint on a whole integer, like 10, will result in subpixel
aliasing. This could be problematic if you're trying to maintain sharpness with your art. (If you want to dive into the
other properties and methods for working with canvas , check out the comprehensive cheat sheet at .
the only context support available when this topic was printed was 2d. there's more about 3d and WebgL
in Chapter 12.
This may look pretty simple, but it's powerful. Keep in mind, too, that you've seen just the beginning of what this
element can do. There are many use cases to cover; going forward, I'll showcase examples of leveraging canvas in
practical approaches, especially as it relates to building online advertisements, including graphical animation, and
handling user inputs.
Search WWH ::

Custom Search