context.stroke()
Causes the perimeter of the Path to be stroked according to the current context.strokeStyle
and the stroked Path is visually drawn onto the canvas.
Prior to executing context.stroke
(or context.fill
) the Path exists in memory and is not yet visually drawn on the canvas.
Consider this example Path that draws a 1 pixel black line from [0,5]
to [5,5]
:
// draw a 1 pixel black line from [0,5] to [5,5]
context.strokeStyle='black';
context.lineWidth=1;
context.beginPath();
context.moveTo(0,5);
context.lineTo(5,5);
context.stroke();
Question: What does the browser actually draw on the canvas?
You probably expect to get 6 black pixels on y=5
But(!) … Canvas always draws strokes half-way to either side of the it’s defined path!
So since the line is defined at y==5.0
Canvas wants to draw the line between y==4.5
and y==5.5
But, again(!) … The computer display cannot draw half-pixels!
So what is to be done with the undesired half-pixels (shown in blue below)?
The answer is that Canvas actually orders the display to draw a 2 pixel wide line from 4.0
to 6.0
. It also colors the line lighter than the defined black
. This strange drawing behavior is “anti-aliasing” and it helps Canvas avoid drawing strokes that look jagged.
An adjusting trick that ONLY works for exactly horizontal and vertical strokes
You can get a 1 pixel solid black line by specifying the line be drawn on the half-pixel:
context.moveTo(0,5.5);
context.lineto(5,5.5);