Code

Canvas

Bezier Curves & Paths

Intermediate Quadratic and cubic Bézier curves, closed polygon paths, the Path2D API, and arcTo for rounded corners. MDN Reference

// Quadratic Bezier (1 control point)
ctx.beginPath();
ctx.moveTo(30, 100);
ctx.quadraticCurveTo(
  150, 10,  // control point
  270, 100  // end point
);
ctx.stroke();

// Cubic Bezier (2 control points)
ctx.beginPath();
ctx.moveTo(310, 100);
ctx.bezierCurveTo(
  360, 10,   // cp1
  450, 130,  // cp2
  490, 60    // end
);
ctx.stroke();

// Closed polygon path (star)
ctx.beginPath();
for (let i = 0; i < points * 2; i++) {
  const angle = i * Math.PI / points - Math.PI / 2;
  const r = i % 2 === 0 ? outer : inner;
  const x = cx + Math.cos(angle) * r;
  const y = cy + Math.sin(angle) * r;
  i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();

// Path2D — reusable path object
const heart = new Path2D();
heart.moveTo(250, 390);
heart.bezierCurveTo(250,370, 210,355, 210,385);
heart.bezierCurveTo(210,415, 250,420, 250,440);
heart.bezierCurveTo(250,420, 290,415, 290,385);
heart.bezierCurveTo(290,355, 250,370, 250,390);
ctx.fill(heart);

// arcTo — tangent-based rounded corners
ctx.beginPath();
ctx.moveTo(40, 490);
ctx.arcTo(40, 530, 100, 530, 20); // radius 20
ctx.arcTo(180, 530, 180, 490, 20);
ctx.stroke();
Key APIs
  • ctx.quadraticCurveTo(cpx, cpy, x, y) — one control point
  • ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) — two control points
  • ctx.arcTo(x1, y1, x2, y2, radius) — arc tangent to two lines
  • ctx.closePath() — draws a line back to the starting point
  • new Path2D() — creates a reusable path object, supports SVG path data strings
  • ctx.isPointInPath(path, x, y) — hit-testing against a Path2D