HTML5 Guidelines for Web Developers

(coco) #1

108 Chapter 5—Canvas


You can find Apple’s Canvas announcement and Ian Hickson’s reaction at:
z http://weblogs.mozillazine.org/hyatt/archives/2004_07.html#005913
z http://ln.hixie.ch/?start=1089635050&count=1

5.1 A First Example


Canvas is, simply put, a programmable picture on which you can draw via a Ja-
vaScript API. In addition to the canvas via the canvas element, we also need a
script element for the drawing commands. Let’s start with the canvas element:

<canvas width="1200" height="800">
alternative content for browsers without canvas support
</canvas>

The attributes width and height determine the dimension of the canvas element
in pixels and reserve the corresponding amount of space on the HTML page.
If one or both attributes are missing, default values come into effect: 300 pixels
for width and 150 pixels for height. The area between the start and end tag is re-
served for alternative content, which will be displayed if a browser does not sup-
port Canvas. Similar to the alt tag for pictures, this alternative content should
describe the content of the Canvas application or show a suitable screen shot.
Phrases like Your browser does not support Canvas without any further informa-
tion are not very helpful and should be avoided.
Our canvas is now finished. In the next step, we can add the drawing commands
in a script element. A few lines of code are enough to turn our first, and admit-
tedly quite trivial, Canvas example into reality:

<script>
var canvas = document.querySelector("canvas");
var context = canvas.getContext('2d');
context.fillStyle = 'red';
context.fillRect(0,0,800,600);
context.fillStyle = 'rgba(255,255,0,0.5)';
context.fillRect(400,200,800,600);
</script>

Even if we do not yet know anything about the syntax of the Canvas drawing com-
mands, the result in Figure 5.1 will not come as a surprise if you look closely at the
code. We now have a red and a light yellow rectangle with 50% opacity, resulting in
an orange tone where the two rectangles overlap.

NOTE
Free download pdf