HTML and CSS Reference
In-Depth Information
The next line in the code is ctx.beginPath(); , and its followed by a sequence of operations to draw
lines or arcs or move a virtual pen. The method ctx.moveTo moves the pen without drawing and
ctx.lineTo specifies the drawing of a line from the current pen position to the point indicated. Please
keep in mind that nothing is drawn until the call of the stroke method. The moveTo , lineTo , and arc
commands set up the path that is drawn whenever either the stroke or fill methods are invoked. In our
draw functions, the next step is calling ctx.stroke(); , and the last step is calling ctx.closePath(); to
end the path. For example, the gallows is drawn by the following function:
function drawgallows() {
ctx.lineWidth = 8;
ctx.strokeStyle = gallowscolor;
ctx.beginPath();
ctx.moveTo(2,180);
ctx.lineTo(40,180);
ctx.moveTo(20,180);
ctx.lineTo(20,40);
ctx.moveTo(2,40);
ctx.lineTo(80,40);
ctx.stroke();
ctx.closePath();
}
The head and the noose require ovals. The ovals will be based on circles, so first I will review how to draw a
circle. You also can go back to Chapter 2. Drawing a circular arc is done with the ctx.arc command with
the following parameters: coordinates for the center of the circle, a length for the radius, the starting angle
in radians, the ending angle, and false for counter-clockwise or true for clockwise. Radians are intrinsic
measurements in which a full circle is Math.PI*2 . The conversion from degrees to radians is to divide by
Math.PI and multiply by 180 , but that is not needed for this example because we are drawing complete
arcs.
However, we want to draw an oval in place of a circle for the head (and later for part of the noose). The
solution is to use ctx.scale to change the coordinate system. In Chapter 4, we changed the coordinate
system to rotate the rectangle representing a cannon. Here, we manipulate the coordinate system to
squeeze one dimension to make a circle an oval. What our code does is first use ctx.save() to save the
current coordinate system. Then for the head, it uses ctx.scale(.6,1); to shorten the x axis to 60
percent of its current value and keep the y axis the same. Use the code for drawing an arc and then use
ctx.restore(); to restore the original coordinate system. The function for drawing the head follows:
function drawhead() {
ctx.lineWidth = 3;
ctx.strokeStyle = facecolor;
ctx.save(); //before scaling of circle to be oval
ctx.scale(.6,1);
ctx.beginPath();
ctx.arc (bodycenterx/.6,80,10,0,Math.PI*2,false);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
 
Search WWH ::




Custom Search