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!
The HTML canvas lineWidth property is used to set or return the width of the line (thickness of the line). The width of the line is set in terms of pixels. The default value of this property is 1.
For drawing straight lines, use the lineTo() method. Draws a line from the current drawing position to the position specified by x and y . This method takes two arguments, x and y , which are the coordinates of the line's end point.
To draw a line on a canvas, you use the following steps: First, create a new line by calling the beginPath() method. Second, move the drawing cursor to the point (x,y) without drawing a line by calling the moveTo(x, y) . Finally, draw a line from the previous point to the point (x,y) by calling the lineTo(x,y) method.
The inline-size CSS property defines the horizontal or vertical size of an element's block, depending on its writing mode. It corresponds to either the width or the height property, depending on the value of writing-mode .
Canvas calculates from the half of a pixel
ctx.moveTo(50,150.5); ctx.lineTo(150,150.5);
So starting at a half will fix it
Fixed version: http://jsfiddle.net/9bMPD/357/
This answer explains why it works that way.
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):
context.translate(0.5, 0.5) context.moveTo(5,5); context.lineTo(55,5);
Keep in mind that if you resize your canvas the translate will be reset - so you'll have to translate again.
You can read about the translate function and how to use it here:
https://www.rgraph.net/canvas/reference/translate.html
This answer explains why it works that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With