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);
Example code using context.stroke()
to draw a stroked Path on the canvas:
<!doctype html>
<html>
<head>
<style>
body{ background-color:white; }
#canvas{border:1px solid red; }
</style>
<script>
window.onload=(function(){
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(50,30);
ctx.lineTo(75,55);
ctx.lineTo(25,55);
ctx.lineTo(50,30);
ctx.lineWidth=2;
ctx.stroke();
}); // end window.onload
</script>
</head>
<body>
<canvas id="canvas" width=100 height=100></canvas>
</body>
</html>