3
votes

LineWidth examples

I've been playing with dashed lines on the HTML5 canvas, and I have run into a roadblock. If I set a LineDash of [2,2,2,2,2] the line looks nearly solid if it's an even number of pixels long. It looks more clearly dashed if it's an odd number of pixels long. I get the same results on my Mac in Firefox, Chrome, and Safari.

Here is simple code showing the effect:

context = document.getElementById("canvas").getContext('2d');
context.lineWidth = 1;
context.strokeStyle = '#990000';
context.setLineDash([2,2,2,2,2]);

// Line ends on an even y-coordinate
context.beginPath();
context.moveTo(2,0);
context.lineTo(2,94);
context.closePath();
context.stroke();

// Line ends on an odd y-coordinate
context.strokeStyle = '#000099';

context.beginPath();
context.moveTo(102,0);
context.lineTo(102,95);
context.closePath();
context.stroke();

Also, neither LineWidth (thickness) nor orientation fix the problem. The problem persists if I change LineWidth from 1 to any other value. And it persists whether the line is horizontal or vertical.

I put a bunch of examples in this codepen: https://codepen.io/anon/pen/ENLwdb

Why should the length matter at all? Shouldn't the dash pattern appear the same regardless of length?

Is my only recourse to alter line lengths if I detect they are even?

1

1 Answers

1
votes

It is because the code is using closePath() on a line which makes it add an extra line on top, from the end point back to the starting point. Depending on the length and pattern the returning line may or may not fill the remaining gaps.

Remove the closePath() (which is only needed to close paths for stroked polygon shapes) and it will work.

Modified CodePen