There is such a javascript code:

function updateGrid() { cntx.strokeStyle = 'white'; cntx.lineCap = 'butt'; cntx.lineWidth = 1; for(var x = 0; x < canvas.width; x++) { cntx.beginPath(); cntx.moveTo(x * cellSize + move.x, move.y); cntx.lineTo(x * cellSize + move.x, canvas.width * cellSize+move.y); cntx.stroke(); cntx.closePath() } } 

He is supposed to draw canvas.width white lines, one pixel thick. But it turns out that in the screenshot:

On some forum I read that cntx.beginPath(); line cntx.beginPath(); can help cntx.beginPath(); . But without it, something even stranger is drawn:

On another forum they said that the line width may be less than one. In the following picture, the width is .0 , without the string cntx.beginPath(); :

And this is with her:

Tell me how to get rid of it?

    2 answers 2

    When trying to draw a line 1px wide, using the coordinates x=(1, 0); y=(1, 3); will be covered at 0.5px on each side of the line, with the result that it will be 2px wide.

    This is due to the inability of the display to display half pixel.

    Given


    In order to output a line 1px wide, you need to calculate the coordinate from the half-pixel, that is, instead of x=(1, 0); y=(1, 3); will be x=(1.5, 0); y=(1.5, 3)

    As a result, the browser will draw a line spanning 0.5px on each side, thereby obtaining a 1px .

    Result

    An example . The first line is #ffffff and the second is #808080 . The difference is only in coordinates.


    Differences in colors are due to the smoothing that is mentioned in the question.

    antialiasing

    When a line passes through a half-pixel, it turns gray, otherwise the image will be jagged. The color of the pixel is selected in the smoothing process, which takes into account the gamma. Pixels will be colored intermediate between the image color and the background color.

    Similar actions occur in your case.

    In this case, you cannot disable anti-aliasing, it would be possible if you use drawImage .


    Canvas - Dive Into HTML5

      Apparently, you define the dimensions of the canvas through the styles, but through the attributes of the canvas .

       <canvas width="100" height="200"></canvas> 

      Otherwise, the image is stretched from the default size.

      Another feature : on retina screens, double the number of points, so the size for such screens needs to be reduced: in attributes, for example, set width="200" , and in styles width:100px

      I will add:

      There is another feature when you draw a line, it appears with coordinates between two pixels. Therefore, you should either add 0.5 to your coordinates:

       context.lineTo(x + 0.5, y + 0.5); 

      Or do so:

       ctx.translate(0.5, 0.5);