Path

The canvas paths allow you to draw custom shapes.

A path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of different color. A path, or even a sub-path (from moveTo), can be closed.

Note that fill() and stroke() are applied to the current path only and the shapes that are not defined in any path!

To make shapes using paths execute the following steps:

  1. Create the path.
  2. Use drawing commands to draw into the path: moveTo, lineTo, arc, arcTo, rect, bezierCurveTo, quadraticCurveTo).
  3. Close the path.
  4. Once the path has been created, you can stroke or fill the path to render it.

Functions:

#

Bezier path:

Bezier curves, available in both cubic and quadratic varieties. These are generally used to draw complex organic shapes.

To Do

Try the following options:

  1. Draw a point:
    ctx.beginPath();
    ctx.arc(20, 20, 5, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fill();
  2. See how the path is closed by the actual line on stroke without defining this line.
    ctx.beginPath();
    ctx.moveTo(20,20);
    ctx.lineTo(100,20);
    ctx.lineTo(100,100);
    ctx.lineTo(20,100);
    ctx.closePath();
    ctx.stroke();
  3. Another example of closing the path and starting ne line from the end path point.
    ctx.beginPath();
    ctx.strokeStyle = 'red';
    ctx.moveTo(50,100);
    ctx.lineTo(100,150);
    ctx.lineTo(150,100);
    ctx.closePath();
    ctx.lineTo(50,50);
    ctx.stroke();
  4. Bezier quadratric curves example:
  5. ctx.beginPath();
    ctx.moveTo(75,25);
    ctx.quadraticCurveTo(25,25,25,62.5);
    ctx.quadraticCurveTo(25,100,50,100);
    ctx.quadraticCurveTo(50,120,30,125);
    ctx.quadraticCurveTo(60,120,65,100);
    ctx.quadraticCurveTo(125,100,125,62.5);
    ctx.quadraticCurveTo(125,25,75,25);
    ctx.stroke();