在画布中绘制 1px 粗线会创建 2px 粗线

2022-01-17 00:00:00 line javascript html html5-canvas

在这个 jsfiddle 中有一条 lineWidth 为 1 的线.

In this jsfiddle there's a line with a lineWidth of 1.

http://jsfiddle.net/mailrox/9bMPD/350/

例如:

ctx.lineWidth = 1;

但是在画布上绘制的线条是 2px 粗的,你如何创建一个 1px 粗的线条.

However the line is 2px thick when it's drawn on the canvas, how do you create a 1px thick line.

我可以绘制一个矩形(高度为 1 像素),但我希望这条线也适用于对角线.那么如何让这条线达到 1px 高呢?

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?

谢谢!

推荐答案

Canvas 从半个像素开始计算

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

固定版本:http://jsfiddle.net/9bMPD/357/

这个答案解释了为什么它会这样工作.

This answer explains why it works that way.

相关文章