javascript - 如何在 HTML5 Canvas 中正确创建带边框的线

标签 javascript html canvas html5-canvas line

我想在 html 中绘制一 strip 有边框的线条路径,以在 map 中渲染街道,但我找不到任何标准方法来做到这一点,所以我资源绘制两条叠加的线,第一条比第二。第一次尝试实际上效果很好:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1000" height="1000" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>

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

ctx.strokeStyle = "black";
ctx.lineWidth = 20;

ctx.moveTo(100,100);
ctx.lineTo(100,900);
ctx.lineTo(900,900);
ctx.stroke();

ctx.strokeStyle = "yellow";
ctx.lineWidth = 16;

ctx.moveTo(100,100);
ctx.lineTo(100,900);
ctx.lineTo(900,900);
ctx.stroke();

</script> 

</body>
</html>

问题是我必须在一个步骤中绘制整个路径,然后在另一步骤中绘制第二个路径。由于这个想法是随着路径的增长而增加路径的长度,所以这是不希望的(我必须重新绘制所有内容,只是为了在路径中添加一个额外的点)。除此之外,第一行和第二行的代码完全重复。

我找到的解决方案是平行绘制两条线。该元素的代码如下:

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

ctx1.strokeStyle = "black";
ctx1.lineWidth = 20;

ctx2.strokeStyle = "yellow";
ctx2.lineWidth = 16;

ctx1.moveTo(100,100);
ctx2.moveTo(100,100);

/* Those two lines can be wrapped in a single function to reduce redundancy of code */
ctx1.lineTo(100,900);
ctx2.lineTo(100,900);

ctx1.lineTo(900,900);
ctx2.lineTo(900,900);

ctx1.stroke();
ctx2.stroke();

但它没有按预期工作。显然这是因为同一个元素不能有两个不同的上下文。

任何人都可以更好地了解如何在 html5 中制作带边框的线条吗?

最佳答案

您不必画两次线。恢复到您的第一个解决方案,只需更改您想要的属性 - ctx.lineWidth = 16ctx.strokeStyle = "yellow" - 然后 ctx.lines()再次

我通过 this answer 发现了这一点描述了如何从 Canvas 上删除:jsfiddle here .

关于javascript - 如何在 HTML5 Canvas 中正确创建带边框的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874375/

相关文章:

javascript - 确认删除模态/对话框在部分 View 中使用时不起作用

javascript - Web Worker 中用于 HTML 字符串内容的类 DOM API

ios - 调整 UIImage 的 Canvas 大小并用颜色填充空白处?

javascript - 连接 javascript 事件并传递参数

javascript - 按特定顺序创建新数组

javascript - 在 Javascript 中读取 session var

html - CSS3 文本渐变不起作用?

html - CSS 背景边距顶部效果

javascript - 像素在 Canvas 上的尺寸不正确

javascript - 为什么这些圆圈会出现在我的 Canvas 上?