如何在HTML5画布中正确创建带有边框的线 [英] How create a line with borders in HTML5 canvas properly

查看:74
本文介绍了如何在HTML5画布中正确创建带有边框的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在html中绘制带有边界的线的路径,以在地图上渲染街道,但是我找不到任何标准的方法来做,所以我设法绘制了两条重叠的线,第一条线比第二.第一次尝试实际上效果很好:

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

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

Anyone could have a better idea of how to make a line with borders in html5?

推荐答案

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

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.

我是通过此答案发现的,该答案描述了如何从画布上擦除:

I discovered this via this answer that describes how to erase from a canvas: jsfiddle here.

这篇关于如何在HTML5画布中正确创建带有边框的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆