HTML and CSS Reference
In-Depth Information
This snippet
ctx.fillStyle = "rgb(0,0,255)";
ctx.fillRect(x,y,w,h);
draws a solid blue rectangle at the indicated position and dimensions. If you want to draw a blue rectangle
with a red outline, you use two lines of code:
ctx.fillRect(x,y,w,h);
ctx.strokeRect(x,y,w,h);
HTML5 lets you draw so-called paths consisting of arcs and line segments. Line segments are drawn
using a combination of ctx.moveTo and ctx.lineTo . Ill cover them in a number of chapters: for the
slingshot game in Chapter 4, the memory game using polygons in Chapter 5, and Hangman in Chapter 9. In
the cannon ball game in Chapter 4, Ill also show you how to tilt a rectangle, and the Hangman game in
Chapter 9 demonstrates how to draw ovals. In this chapter, Ill focus on the arcs.
You start a path using
ctx.beginPath();
and end it, with the path being drawn, with either
ctx.closePath();
ctx.stroke();
or
ctx.closePath();
ctx.fill();
An arc can be a whole circle or part of a circle. In the dice applications, we draw only whole circles to
represent the pips on the face of each die, but Ill explain how arcs work in general to make the code less
mysterious. The method for drawing arcs has the following format:
ctx.arc(cx, cy, radius, start_angle, end_angle, direction);
where cx , cy, and radius are the center horizontal and vertical coordinates and the radius of the circle.
To explain the next two parameters requires discussing ways to measure angles. Youre familiar with the
degree unit for angles: we speak of making a 180-degree turn, meaning a u-turn, and a 90-degree angle is
produced by two perpendicular lines. But most computer programming languages use another system,
called radians . Heres one way to visualize radians—think of taking the radius of a circle and laying it on
the circle itself. You can dig into your memory and realize that it won't be a neat fit, because there are 2*
PI radians around the circle, somewhat more than 6. So if we want to draw an arc that is a whole circle, we
specify a starting angle of 0 and an end angle of 2*PI. Luckily, the Math class furnishes a constant
Math.PI that is the value of PI (to as much accuracy, as many decimal places, as necessary), so in the
code, we write 2*Math.PI . If we want to specify an arc that is half a circle, we use Math.PI , while a right-
angle (90 degrees) will be .5*Math.PI .
The arc method requires one more argument, direction. How are we drawing these arcs? Think of the
movement of the hands on a clock face. In HTML 5, clockwise is the false direction and counterclockwise
is the true direction. (Don't ask why. Thats just the way its specified in HTML5.) I use the built-in
JavaScript values true and false . This will be important when we need to draw arcs that are not whole
circles. The nature of the particular problem dictates how you define the angles if you need to draw arcs
that are not full circles.
 
Search WWH ::




Custom Search