Examples of More Advanced Line Drawing

Example 2-3 shows these attributes in action; the results are depicted in Figure 2-3. There are a few oddities when drawing lines on the canvas, which we will point out along the way.

Example 2-3. Line cap and join

function drawScreen() {

      // Sample 1: round end, bevel join, at top left of canvas
      context.strokeStyle  = "black";
      context.lineWidth  = 10;
      context.lineJoin  = 'bevel';
      context.lineCap  = 'round';
      context.beginPath();
      context.moveTo(0, 0);
      context.lineTo(25, 0);
      context.lineTo(25,25);
      context.stroke();
      context.closePath();

      // Sample 2: round end, bevel join, not at top or left of canvas
      context.beginPath();
      context.moveTo(10, 50);
      context.lineTo(35, 50);
      context.lineTo(35,75);
      context.stroke();
      context.closePath();

      // Sample 3: flat end, round join, not at top or left of canvas
      context.lineJoin  = 'round';
      context.lineCap = 'butt';
      context.beginPath();
      context.moveTo(10, 100);
      context.lineTo(35, 100);
      context.lineTo(35,125);
      context.stroke();
      context.closePath();

   }
Line cap and join

Figure 2-3. Line cap and join

These three line and join samples should help illustrate some of the combinations of attributes we can use to draw paths on the canvas.

The first sample attempts to draw starting at the top left of the canvas, resulting in a strange image. Canvas paths are drawn outward in both the x and y directions from the center of the pixel it begins on. For this ...

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.