Gabriel Diego
Gabriel Diego

Reputation: 1020

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

Upvotes: 1

Views: 9726

Answers (1)

Henry Blyth
Henry Blyth

Reputation: 1750

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.

Upvotes: 5

Related Questions