beginPath() 简介
beginPath() 是 Canvas 2D 上下文中用于开始一条新路径的方法。它告诉画布:”接下来的绘制是一个新的独立图形,不要和之前的路径连在一起。”
语法
ctx.beginPath();
无参数,无返回值。
为什么需要 beginPath()
Canvas 的路径绘制是累积式的。如果不调用 beginPath(),新绘制的图形会与之前未闭合的路径合并,导致意外的连线或样式混乱。
错误示例(不使用 beginPath):
ctx.strokeStyle = 'red';
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.stroke();
ctx.strokeStyle = 'blue'; // 想画一条蓝色的线
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke(); // 结果:两条线都变成蓝色!
因为第二条线是在原有路径上继续添加,而 strokeStyle 只对最后一次 stroke() 生效,所以第一条线的颜色也被覆盖了。
正确用法
// 第一条线(红色)
ctx.beginPath(); // 开启新路径
ctx.strokeStyle = 'red';
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.stroke();
// 第二条线(蓝色)
ctx.beginPath(); // 再次开启新路径
ctx.strokeStyle = 'blue';
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
典型使用场景
1. 绘制多个独立图形:
// 圆形
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
// 矩形
ctx.beginPath();
ctx.rect(200, 25, 100, 100);
ctx.fillStyle = 'blue';
ctx.fill();
2. 在同一图形中使用不同样式:
// 先描边再填充同一个形状
ctx.beginPath();
ctx.arc(150, 110, 70, 0, Math.PI * 2);
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.stroke();
ctx.beginPath(); // 重新开始路径
ctx.arc(150, 110, 65, 0, Math.PI * 2);
ctx.fillStyle = 'yellow';
ctx.fill();
与其他路径方法的关系
| 方法 | 作用 |
|---|---|
beginPath() |
重置路径列表,开始新路径 |
closePath() |
闭合当前路径(连接起点和终点) |
moveTo() |
移动画笔到指定点(不画线) |
lineTo() |
从当前位置画线到指定点 |
注意事项
beginPath()不会清除已经绘制到画布上的内容,只清空路径记录- 每次调用
stroke()或fill()后,路径仍然保留,下次绘制前最好先调用beginPath() - 使用
fill()时会自动闭合路径(即使没调用closePath()),但stroke()不会
一句话总结
每次开始绘制一个新图形之前,先调用 ctx.beginPath(),避免路径混乱和样式污染。
