In this jsfiddle there's a line with a lineWidth of 1.
http://jsfiddle.net/mailrox/9bMPD/350/
e.g:
ctx.lineWidth = 1;
However the line is 2px thick when it's drawn on the canvas, how do you create a 1px thick line.
I could draw a rectangle (with 1px height) however I want the line to also work on diagonals. So how do you get this line to be 1px high?
Thanks!
For me, only a combination of different 'pixel perfect' techniques helped to archive the results:
Get and scale canvas with the pixel ratio:
pixelRatio = window.devicePixelRatio/ctx.backingStorePixelRatio
Scale the canvas on the resize (avoid canvas default stretch scaling).
multiple the lineWidth with pixelRatio to find proper 'real' pixel line thickness:
context.lineWidth = thickness * pixelRatio;
Check whether the thickness of the line is odd or even. add half of the pixelRatio to the line position for the odd thickness values.
x = x + pixelRatio/2;
The odd line will be placed in the middle of the pixel. The line above is used to move it a little bit.
Resize event is not fired in the snipped so you can try the file on the github
You can also translate by half a pixel in the X and Y directions and then use whole values for your coordinates (you may need to round them in some cases):
Keep in mind that if you resize your canvas the translate will be reset - so you'll have translate again.
This answer explains why it works that way.
Or as this answer states, to get a width of 1, you need to start at a half pixel.
http://jsfiddle.net/9bMPD/355/
The Canvas can draw clean straight lines with fillRect(). A rectangle with a 1px height or a 1px width does the job. It doesn't need half-pixel value:
https://jsfiddle.net/ynur1rab/
The fillRect() method can be used to draw thin horizontal or vertical lines in canvas (without having to apply the +0.5 shift on coordinates):
And you can actually make the lines even thinner by just replacing this code by something like:
Lines will be thinner (tending to reach 1 pixel wide) but their color a bit attenuated.
-> working example
To be noted that if we set ctx.lineWidth=0.7 (for the classical beginPath/moveTo/lineTo/stroke sequence), it does not work on Chrome (0.7 and 1 are interpreted the same way). Thus an interest for this fillRect() method.
Did you see the first hit on google? (search for
canvas line width 1px
). Though I have to admit this isn't exactly "clean" or "lean". Ferry Kobus' solution is much better. Then again: it sucks you need to use "half pixels" in the first place...