【问题标题】:Do I have to have the content.beginPath() and content.closePath()?我是否必须拥有 content.beginPath() 和 content.closePath()?
【发布时间】:2014-03-16 10:03:52
【问题描述】:

是否必须包含 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();

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    不,beginPath 和 closePath 不是必需的。

    画布上下文具有当前路径。您可以使用 moveTo 和 lineTo 等方法向该路径添加指令。完成路径构建后,可以使用stroke 和fill 等方法,使用当前路径在画布上进行绘制。

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

    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 会丢弃以前的路径并让您开始新的路径。没有它,您将越来越多地附加到先前的路径,这可能是不可取的。比较和对比:

    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();
    

    【讨论】:

    • 这些路径是否保存在画布中,以便您可以从索引类型情况中调用它们。在上面的示例中,您没有 beginPath() endPath() 所以这些只是附加到旧画布上。
    • @user3376708:一次只保存一个路径,beginPath 将其丢弃。如果您想要返回旧路径,则必须致电beginPath 丢弃当前路径,然后根据单独的说明重建旧路径。 (我不太明白您所说的“索引类型情况”是什么意思。)
    【解决方案2】:

    beginPath() 清除旧路径,以便您定义新路径。

    closePath() 将第一个点与最后一个点连接起来,在您的示例中不需要。在任何情况下,它都会在填充描边之前使用,以对光栅化结果产生影响。

    【讨论】:

    • 有没有办法召回以前使用过的路径。您能否在画布中有五个 beginPath() 和五个 closePath() 并回忆第二条路径。
    • 将来您可以使用单独的 Path 对象。但是,目前还没有浏览器可以完全实现这一点。您现在需要重新创建一个路径。
    • 使用路径对象会有好处,所以最好是有理由地使用它们。
    猜你喜欢
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多