HTML and CSS Reference
In-Depth Information
<canvas id="adCanvas" width="100" height="100"></canvas>
As you can see, it's fairly simple to create the tag in HTML5. If you open your favorite text editor, input the
Listing 4-1 code, save it as canvas.html , and open it in your favorite modern browser, you'll notice that nothing is
rendered to the screen. Don't be alarmed; think of it as an artist placing his canvas on the easel—and this time you're
the artist, though you haven't actually started to draw anything yet. To draw on canvas , you'll need to leverage the
real power of this new HTML5 element; that's in its API, which is all JavaScript. JavaScript controls the painting of
graphics, animation, and interactivity. (It's best to think of the element as a container or shell for graphics that you will
create by leveraging JavaScript.)
Before heading into JavaScript implementation of canvas , note that the element has a few DOM attributes,
including width and height, within the HTML markup.
doM refers to a page's document markup, which is made up of elements, attributes and tags. the canvas
element is part of the doM structure, which can have various attributes, including ID , Class , Height , and Width .
More importantly, canvas has several methods for drawing paths, shapes, gradients, and characters, as well as
adding images and compositing. And that's only for starters! The element can be instructed to do many things besides
detecting user input and rendering complex animations—interactive games, for instance. It can even be used multiple
times either in the browser, by creating a stack of canvas elements, one on top of another, to represent a complex
image composite, or even on different areas of the page. It's really up to you, as developer and designer, to leverage
this powerful new addition to the Web.
Let's build on the code in Listing 4-1 to render a green square to the screen by adding some simple JavaScript
code. Try to follow along in your text editor in Listing 4-2.
Listing 4-2. Using Canvas to Render a Green Square to the Screen
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<canvas id="adCanvas" width="300" height="250"></canvas>
<script type="text/javascript">
//get a reference to the canvas
var canvas = document.getElementById('adCanvas');
var context = canvas.getContext('2d');
//draw a green square
context.fillStyle = 'green';
context.fillRect(0, 0, 250, 250);
Once you refresh your page, you should get an image of a small green square, as shown in Figure 4-1 .
Search WWH ::

Custom Search