Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Drawing by using the element CHAPTER 12 481


ctx.moveTo(300, 300);
ctx.lineTo(350, 250);
ctx.lineTo(400, 300);
ctx.rect(300, 300, 100, 100);
ctx.stroke();
ctx.fill();
}

The rendered output of the outline of the second shape is narrow compared to the outline
of the first shape, and the second shape does not have the horizontal line of the triangle.
These differences result from the fill method being called after the stroke method, so the fill
color overwrites any previous color.

Drawing arcs by using the arcTo method
In addition to drawing straight lines, you can draw curved lines by using the arc and the arcTo
methods on the context object.
The arcTo method accepts an x1 and a y1 coordinate that define a point through which the
arc lines must pass, followed by an x2 and a y2 coordinate that define the endpoint, followed
by the radius of the arc. Although only two points are provided as parameters, a third point
(x0, y0) is the starting point of the arc. The third point is the ending point of the previous
sub-path.
Drawing an arc by using the arcTo method can be confusing. To understand how arcTo
works, perform the following steps.


  1. On a piece of paper, draw a line through (x0, y0) and (x1, y1).

  2. Draw a line through (x1, y1) and (x2, y2).

  3. On a separate piece of paper, draw a circle of radius r and cut it out.

  4. Place the circle on the paper that has the two lines and slide the circle up between the
    line that contains (x0, y0) and the line that contains (x2, y2) until it just touches both
    lines. The two points where the circle touches the lines are called tangent points, where
    t1 is closest to (x0, y0), and t2 is closest to (x2, y2).

  5. Draw a line from point (x0, y0) to the first tangent point on the line from (x0, y0) to
    (x1, y1).

  6. Draw an arc from that tangent point to the other tangent point on the line from
    (x1, y1) to (x2, y2) along the circumference of the circle.

  7. The endpoint of arcTo is the second tangent point on the line from (x1, y1) to (x2, y2).
    Figure 12-13 shows two examples of the arcTo implementation.

Free download pdf