ctx.stroke() 和 ctx.fill() 是否自动关闭 canvas 中的路径?

Does ctx.stroke() and ctx.fill() automatically close path in canvas?

如果我在 canvas 中绘制路径时要使用 ctx.fill() 或 ctx.stroke(),是否有必要包含 ctx.closePath()?
下面是一个例子:

ctx.beginPath()
// point 1
ctx.moveTo(x+0.5,y+0.5)
// point2
ctx.lineTo(x2+0.5, y2+0.5)
// point 3
ctx.lineTo(x3+0.5, y3+0.5)

ctx.closePath() // <--- IS THIS NECESSARY ?
ctx.stroke()

该函数按照它说的做,它关闭了路径,如果你想要在你的例子中有一个封闭的三角形,那么 closepath() 是必需的,如果你想要两条线,那么它不是。

所以你的问题的答案是:不,stroke()fill() 不会关闭你的路径。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

let x = 10;
let y = 10;

ctx.beginPath()
// point 1
ctx.moveTo(x/2+0.5,y/2+0.5)
// point2
ctx.lineTo(x*2+0.5, y*4+0.5)
// point 3
ctx.lineTo(x*3+0.5, y*2+0.5)

ctx.closePath() // <--- IS THIS NECESSARY ?
ctx.stroke()

// New path

x = 50;
y = 20;

ctx.beginPath()
// point 1
ctx.moveTo(x+0.5,y+0.5)
// point2
ctx.lineTo(x*2+0.5, y*4+0.5)
// point 3
ctx.lineTo(x*3+0.5, y*2+0.5)

ctx.stroke()
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>