Wednesday, October 12, 2011

HTML5 Canvas Drawing Lines

The future of GUI is HTML5. Just ask Microsoft.
And this includes graphics, too.

I have observed a strange issue that lines show 2-pixel wide,
even when "stroke" width is selected to be 1 pixel.
As usual, there is a rational and useful explanation and solution...

This good (free online) book has answers to right questions...

Canvas - Dive Into HTML5 by Mark Pilgrim (@ Google)

for (var x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0);
  context.lineTo(x, 375);
}
Q: Why did you start x and y at 0.5? Why not 0?

A: Imagine each pixel as a large square. The whole-number coordinates (0, 1, 2…) are the edges of the squares. If you draw a one-unit-wide line between whole-number coordinates, it will overlap opposite sides of the pixel square, and the resulting line will be drawn two pixels wide. To draw a line that is only one pixel wide, you need to shift the coordinates by 0.5 perpendicular to the line's direction.

For example, if you try to draw a line from (1, 0) to (1, 3), the browser will draw a line covering 0.5 screen pixels on either side of x=1. The screen can’t display half a pixel, so it expands the line to cover a total of two pixels:

A line from (1,0) to (1,3) is drawn 2 pixels wide

But, if you try to draw a line from (1.5, 0) to (1.5, 3), the browser will draw a line covering 0.5 screen pixels on either side of x=1.5, which results in a true 1-pixel-wide line:

A line from (1.5,0) to (1.5,3) is draw 1 pixel wide

No comments: