HTML5 Canvas Issue: Half-Pixel Offset

One of the issues I encountered when working with the HTML5 canvas element was the issue of pixel alignment. I made sure that the only size definition was given in the HTML declaration for the image itself as in:

…which means that the canvas pixels will always line up with physical screen pixels. The issue is how the actual coordinates are specified when drawing on the canvas. Every other screen coordinate system I’ve used drew nice lines on even pixel boundaries. That is, you specify the pixel locations as whole numbers. Usually you translate between your internal, floating point coordinate space to the integer pixel space by adding one half and truncating. When I did that, however, the lines ended up getting drawn across two pixels. When I added an extra half-pixel offset the lines were drawn across only a single pixel. This effect is most noticeable when the lines are horizontal or vertical. The following diagram from the Mozilla canvas tutorial illustrates the issue.

I added a button which toggles the pixel offset between 0.0 and 0.5 and redraws the figure to show the effect.

This entry was posted in Software and tagged , . Bookmark the permalink.

Leave a Reply