Monday, 16 April 2012

Why your canvas paths could be to wide


This is a quick tip about drawing paths on the HTML5 canvas element and why your lines maybe wider than you wanted them, it's all to do with the fact that you can't draw a half pixel.

What's the problem?

To draw a line on a HTML5 canvas you first tell it where to start using context.moveTo(x, y); then tell it where to end using context.lineTo(x, y); and afterwards set it's colour and stroke properties. The problem is that HTML5 canvas draws a line at an equal width either side of those defined points, but if you want a 1 pixel thick line and define its start and end points as being a whole number then it would need to draw a line 0.5 pixels either side of that point to create a 1 pixel line. As it cannot draw half a pixel it will instead be forced to draw a whole pixel either side of the start point and create a 2 pixel wide line instead of the 1 pixel line you wanted.

The solution

The solution is quite simple, instead of defining your start and end points as whole pixels define them as a half pixel, and example of the correct method and incorrect method of drawing a 1 pixel thick, black 100 pixel long line is below.

Incorrect example

context.moveTo(1, 1);
context.lineTo(1, 100);
context.strokeStyle = "#000000";
context.stroke();

Correct example

context.moveTo(1.5, 1);
context.lineTo(1, 100);
context.strokeStyle = "#000000";
context.stroke();

Further reading

1 comment: