Drawing clean and thin vertical and horizontal lines on an HTML Canvas

I saw this morning on StackOverflow a question whose lack of answer prompted me to make a detailed one and an explanation.

Canvas positioning is in float. And round values are between pixels.

A consequence is that if you draw a line with a lineWidth of 1, the results will extend over two pixels if you don’t target the middle of the pixel.

On the following schema, the first horizontal line was drawn with a y position of 1. This line is fuzzy and wide. The second horizontal line was drawn with a y position of 4.5. It is thin and precise.

And it gets worse if instead of using round values you use any kind of float values : the result is very irregular.

A consequence is that in order to draw thin lines, you have to adapt the y position before.

I made two functions to draw thin vertical or horizontal lines and I use them on all my canvas based projects :

	function drawThinHorizontalLine(c, x1, x2, y) {
		c.lineWidth = 1;
		var adaptedY = Math.floor(y)+0.5;
		c.beginPath();
		c.moveTo(x1, adaptedY);
		c.lineTo(x2, adaptedY);
		c.stroke();
	}
	function drawThinVerticalLine(c, x, y1, y2) {
		c.lineWidth = 1;
		var adaptedX = Math.floor(x)+0.5;
		c.beginPath();
		c.moveTo(adaptedX, y1);
		c.lineTo(adaptedX, y2);
		c.stroke();
	}

Les commentaires sont fermés.