gpt4 book ai didi

javascript - 我必须有 content.beginPath() 和 content.closePath() 吗?

转载 作者:技术小花猫 更新时间:2023-10-29 12:17:24 25 4
gpt4 key购买 nike

是否必须包含 beginPath 和 closePath 才能绘制这条线或所有图形。我有一本新的 HTML 5 Canvas 书,但我并不完全确定。我注释掉了这两行,该行仍然显示。这两行有什么意义。

问题:beginPath() 和 closePath() 的作用是什么?

代码:

context.lineJoin='round';
context.lineCap='butt';
context.beginPath();
context.moveTo(10, 100);
context.lineTo(35, 100);
context.lineTo(35,125);
context.stroke();
context.closePath();

最佳答案

不,beginPathclosePath 不是必需的。

Canvas 上下文有一个当前路径。您可以使用 moveTolineTo 等方法向该路径添加指令。路径构建完成后,可以使用 strokefill 等方法,使用当前路径在 Canvas 上绘制。

closePath 只是您可以添加的另一条指令。在使用 fill 时您可能不会注意到它的效果,但是在使用 stroke 时,它会(基本上)做一条线回到起始位置,“关闭”路径。比较和对比:

two lines a triangle

ctx.moveTo(10, 10);    ctx.moveTo(10, 10);
ctx.lineTo(90, 10); ctx.lineTo(90, 10);
ctx.lineTo(90, 90); ctx.lineTo(90, 90);
ctx.closePath();
ctx.stroke(); ctx.stroke();
另一方面,

beginPath 会丢弃以前的路径并让您开始一个新路径。没有它,您将越来越多地附加到以前的路径,这可能是不可取的。比较和对比:

a double-red-blue stroked line and a blue line a red line and a blue line

ctx.moveTo(10, 10);           ctx.moveTo(10, 10);
ctx.lineTo(90, 10); ctx.lineTo(90, 10);
ctx.lineWidth = 4; ctx.lineWidth = 4;
ctx.strokeStyle = "red"; ctx.strokeStyle = "red";
ctx.stroke(); ctx.stroke();
ctx.beginPath();
ctx.moveTo(10, 20); ctx.moveTo(10, 20);
ctx.lineTo(90, 20); ctx.lineTo(90, 20);
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.strokeStyle = "blue"; ctx.strokeStyle = "blue";
ctx.stroke(); ctx.stroke();

关于javascript - 我必须有 content.beginPath() 和 content.closePath() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432036/

25 4 0
文章推荐: html - 如果有打开的 `if` 标签,Razor `}` 不会注册关闭 ``?