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

Wednesday, 11 April 2012

Lack of posts

Hello,

I just thought I'd explain a little about why I haven't posted in a little white, I'm planning on switching away from Blogger to Wordpress as I want to integrate this more with my portfolio site (once it is built) and add more to this such as a dedicated area for my secure PHP login project and articles about web development.

I should hopefully have part of the switch done by the end of the weekend, enough so that the basic structure of the site is done (not necessarily the overall design) and the fact that it'll be running on Wordpress so I can continue posting again. I've got a few posts written up just waiting for you all to read.