tags:

views:

93

answers:

3

I am reading a book on Html5 and about canvas, the following code will generate 1-pixel thick lines... It uses 0.5 as the coordinate. If it is changed to 0 or 10, or some integer, then the lines will be gray, and 2-pixel thick. Why is that? That the strangest thing I have seen lately... all the programming before on Apple or Win32 API, they go by integer coordinates.

<!DOCTYPE html>

<body>
<canvas id="c" width="800" height="600"></canvas>
</body>

<script>

var c_canvas = document.getElementById("c")
var context = c_canvas.getContext("2d")

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0)
  context.lineTo(x, 375)
}
context.strokeStyle = "#000"
context.stroke()


</script>

Another strange thing is, to get a 1 pixel by 1 pixel black dot, I have to draw on 0.5 for x, but use integers for y

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0)
  context.lineTo(x, 1)
}

if I use the following, then I get a gray, "longer dot"

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0.5)
  context.lineTo(x, 1.5)
}
+3  A: 

I am not sure it it is the same with HTML5, but it looks very similar to how the Qt library deals with painting. Essentially, the (0,0) and (1,1) coordinates define a pixel in the top left corner - its center is thus located at (0.5, 0.5).

It has to do with antialiasing - if you "draw" a black pixel at (1,1), 4 gray pixels will actually be painted gray, between (0,0) and (2,2). Read more about this in C++ GUI programming with Qt 4.

MiKy
+1  A: 

thanks MiKy. I also found some explanation on

https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors#A_lineWidth_example

動靜能量
+1 - Link has the best explanation, with some good diagrams.
Castrohenge
+2  A: 

In a nutshell, pixels cannot be divided. When you use lineTo to draw a 1 pixel line, the line is centered on the coordinate that you specify. If width=1 and the coordinate is an integer, then you are asking to draw 2 halves of a pixel.

Since you can't turn on half a pixel, the library rounds to the nearest divisible pixel on either side.

Error 454