The Actual Drawing

The most basic path is controlled by a series of moveTo() and lineTo() commands, as shown in Example 2-2.

Example 2-2. A simple line path

function drawScreen() {
   context.strokeStyle  = "black";
   context.lineWidth  = 10;
   context.lineCap  = 'square';
   context.beginPath();
   context.moveTo(20, 0);
   context.lineTo(100, 0);
   context.stroke();
   context.closePath();

}

Figure 2-2 shows an example of this output.

A simple line path

Figure 2-2. A simple line path

Example 2-2 simply draws a 10-pixel-wide horizontal line (or stroke) from position 20,0 to position 100,0.

We have also added the lineCap and strokeStyle attributes. Let’s take a brief look at the various attributes we can apply to a line before we move on to some more advanced drawing. The context.stroke(); command will finalize and draw the line we have constructed.

lineCap attributes

context.lineCap

The lineCap is the end of a line drawn on the context. It can be one of three values:

butt

The default; a flat edge that is perpendicular to the edge of the line.

round

A semicircle that will have a diameter that is the length of the edge of the line.

square

A rectangle with the length of the line width and the height of half the line width, placed flat and perpendicular to the edge of the line.

lineJoin attributes

context.lineJoin

The lineJoin is the “corner” that is created when two lines meet. This is called a join. A filled triangle is created at the join, ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.