简体   繁体   English

如何正确地在HTML5画布中创建带边框的线条

[英]How create a line with borders in HTML5 canvas properly

I want to draw a path of lines with borders in html, to render the streets in a map, but I could not find any standard way to do that, so I resourced to draw two superposed lines, the first one thicker than the second. 我想在html中绘制一条带边框的线条,在地图中渲染街道,但我找不到任何标准的方法来做到这一点,所以我资源绘制两条叠加的线条,第一条线条比第二条线条粗。 The first attempt actually worked well: 第一次尝试实际上运作良好:

<!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>

The problem is that I would have to draw the entire paths in one step then the second one in another step. 问题是我必须在一个步骤中绘制整个路径,然后在另一个步骤中绘制第二个路径。 Since the idea is to increase the length of the path as it grows, this is not wanted (I would have to redraw everything just to add one extra point in the path). 由于这个想法是在增长时增加路径的长度,所以不需要这样做(我必须重新绘制所有内容,只是为了在路径中添加一个额外的点)。 Besides that the code is totally duplicated for the first and second line. 除此之外,第一行和第二行的代码完全重复。

The solution that I found was to draw the two lines in parallel. 我找到的解决方案是并行绘制两条线。 The code for the element is below: 该元素的代码如下:

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

But it didn't worked as expected. 但它没有按预期工作。 Apparently it is because I can't have two different contexts for the same element. 显然,这是因为我不能为同一个元素设置两个不同的上下文。

Anyone could have a better idea of how to make a line with borders in html5? 任何人都可以更好地了解如何在html5中创建带边框的线条?

You don't have to draw the line twice. 您不必两次绘制线条。 Revert to your first solution and just change the attributes you want - ctx.lineWidth = 16 and ctx.strokeStyle = "yellow" - then ctx.stroke() again. 恢复到你的第一个解决方案,只需更改你想要的属性 - ctx.lineWidth = 16ctx.strokeStyle = "yellow" - 然后再次ctx.stroke()

I discovered this via this answer that describes how to erase from a canvas: jsfiddle here . 我通过这个回答描述了如何从画布中删除: jsfiddle here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM