HTML5 Canvas Tutorial - HTML5 Canvas Path








We can create a path with HTML5 Canvas by connecting multiple subpaths.

The ending point of each new subpath becomes the new starting point.

We can use the lineTo(), arcTo(), quadraticCurveTo(), and bezierCurveTo() methods to construct subpath in the path.

Calling beginPath() method each time starts drawing a new path.

Example


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!--from  w  ww .j a  v  a2s . co  m-->
      context.beginPath();
      context.moveTo(100, 20);

      // line 1
      context.lineTo(100, 160);

      // quadratic curve
      context.quadraticCurveTo(250, 200, 250, 120);

      // bezier curve
      context.bezierCurveTo(90, 40, 150, 200, 400, 150);

      // line 2
      context.lineTo(400, 90);

      context.lineWidth = 5;
      context.strokeStyle = 'red';
      context.stroke();

    </script>
  </body>
</html>      

The code above is rendered as follows:





HTML5 Canvas Line Join

To set the line join style in HTML5 Canvas path, we can use the lineJoin context property.

Paths can have one of three line joins:

  • miter
  • round
  • bevel

HTML5 Canvas line join property defaults to the miter style.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!--from w w w  .j a  v a 2  s. co m-->
      // set line width for all lines
      context.lineWidth = 25;

      // miter line join (left)
      context.beginPath();
      context.moveTo(100, 150);
      context.lineTo(150, 50);
      context.lineTo(200, 150);
      context.lineJoin = 'miter';
      context.stroke();

      // round line join (middle)
      context.beginPath();
      context.moveTo(240, 150);
      context.lineTo(290, 50);
      context.lineTo(340, 150);
      context.lineJoin = 'round';
      context.stroke();

      // bevel line join (right)
      context.beginPath();
      context.moveTo(380, 150);
      context.lineTo(430, 50);
      context.lineTo(480, 150);
      context.lineJoin = 'bevel';
      context.stroke();
    </script>
  </body>
</html>      

The code above is rendered as follows: