closePath() 简介

closePath() 是 Canvas 2D 上下文中用于闭合当前路径的方法。它会从当前画笔位置画一条直线回到当前子路径的起点。

语法

ctx.closePath();

无参数,无返回值。

基本用法

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(100, 50);     // 起点 A
ctx.lineTo(175, 165);    // 画到 B
ctx.lineTo(25, 165);     // 画到 C
ctx.closePath();         // 从 C 画回 A,形成三角形

ctx.stroke();            // 描边显示
// 或者 ctx.fill();      // 填充(fill()会自动闭合路径)

closePath() 的效果对比

不使用 closePath():

A ──── B
       │
       C

三条边中,A→B 和 B→C 画出来了,但 C→A 没有连线,图形不封闭。

使用 closePath():

A ──── B
│      │
└──────C

自动添加 C→A 的连线,形成一个完整的封闭三角形。

与 fill() 的关系

// fill() 会自动闭合路径,不需要手动调用 closePath()
ctx.beginPath();
ctx.moveTo(100, 50);
ctx.lineTo(175, 165);
ctx.lineTo(25, 165);
ctx.fill();              // 自动闭合并填充,效果等同于加了 closePath()

// stroke() 不会自动闭合,需要手动 closePath()
ctx.beginPath();
ctx.moveTo(100, 50);
ctx.lineTo(175, 165);
ctx.lineTo(25, 165);
ctx.closePath();         // 必须手动闭合
ctx.stroke();            // 才能看到完整的三角形边框

典型应用场景

1. 绘制多边形:

// 五角星
ctx.beginPath();
for (let i = 0; i < 5; i++) {
  const angle = (i * 4 * Math.PI) / 5 - Math.PI / 2;
  const x = 150 + 80 * Math.cos(angle);
  const y = 125 + 80 * Math.sin(angle);
  if (i === 0) {
    ctx.moveTo(x, y);
  } else {
    ctx.lineTo(x, y);
  }
}
ctx.closePath();
ctx.fillStyle = 'gold';
ctx.fill();
ctx.strokeStyle = 'darkgoldenrod';
ctx.lineWidth = 2;
ctx.stroke();

2. 绘制饼图扇区:

function drawPieSlice(ctx, cx, cy, radius, startAngle, endAngle, color) {
  ctx.beginPath();
  ctx.moveTo(cx, cy);                      // 圆心
  ctx.arc(cx, cy, radius, startAngle, endAngle);  // 弧线
  ctx.closePath();                         // 回到圆心,形成扇区
  ctx.fillStyle = color;
  ctx.fill();
}

3. 绘制圆角矩形的边框:

function roundRect(ctx, x, y, w, h, r) {
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.arcTo(x + w, y, x + w, y + r, r);
  ctx.lineTo(x + w, y + h - r);
  ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
  ctx.lineTo(x + r, y + h);
  ctx.arcTo(x, y + h, x, y + h - r, r);
  ctx.lineTo(x, y + r);
  ctx.arcTo(x, y, x + r, y, r);
  ctx.closePath();      // 闭合路径,完成圆角矩形
}

注意事项

情况 行为
路径已经是闭合状态 不产生任何效果
路径只有一个点 画一条长度为 0 的线回到自身
配合 fill() 不需要手动调用 closePath()fill() 会自动闭合
配合 stroke() 必须手动调用 closePath() 才能看到封闭边框

一句话总结

closePath() 就是把路径的终点和起点连起来,让图形变封闭。描边时必须手动调用,填充时会自动闭合。