Html 在html5画布中绘制单像素线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9311428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:34:45  来源:igfitidea点击:

Draw single pixel line in html5 canvas

htmlcanvas

提问by Neir0

When i try to draw single pixel black line with the following code:

当我尝试使用以下代码绘制单像素黑线时:

    context.strokeStyle = '#000'; 
    context.beginPath();
    context.moveTo(x1, y1); 
    context.lineTo(x2, y2);
    context.lineWidth = 1;
    context.stroke();
    context.closePath();  

I have more then one pixel line with gray border. How to fix it?

我有超过一条带灰色边框的像素线。如何解决?

Here is an example http://jsfiddle.net/z4VJq/

这是一个例子http://jsfiddle.net/z4VJq/

回答by Jonas

Call your function with these coordinates instead: drawLine(30,30.5,300,30.5);. Try it in jsFiddle.

使用这些坐标,而不是调用你的函数:drawLine(30,30.5,300,30.5);。在jsFiddle 中尝试一下。

The problem is that your color will be at an edge, so the color will be halfway in the pixel above the edge and halfway below the edge. If you set the position of the line in the middle of an integer, it will be drawn within a pixel line.

问题是您的颜色将位于边缘,因此颜色将位于边缘上方像素的一半和边缘下方像素的一半。如果将线的位置设置在整数的中间,它将绘制在像素线内。

This picture (from the linked article below) illustrates it:

这张图片(来自下面的链接文章)说明了这一点:

enter image description here

在此处输入图片说明

You can read more about this on Canvas tutorial: A lineWidth example.

您可以在Canvas 教程中阅读更多相关信息:A lineWidth 示例