HTML5画布和线宽 [英] HTML5 Canvas and Line Width

查看:241
本文介绍了HTML5画布和线宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在画布上绘制线条图。线条画的很好。图形被缩放,每个段被绘制,颜色是确定的等等。我唯一的问题是在视觉上线宽变化。它几乎像一支书法笔的笔尖。如果行程向上,线条很薄,如果行程是水平的,则线条更粗。



我的线条粗细是常数,我的 strokeStyle 设置为 black 。我没有看到任何影响这种变化线宽的画布属性,但必须有。

解决方案


从(3,1)到(3,5)的路径,线粗度为
1.0,则结果是第二张图像中的情况。要填充的实际
区域(深蓝色)仅延伸到路径两侧的
像素中途。必须渲染这种情况的近似值
,这意味着那些像素只有部分阴影,并且在整个区域(浅蓝色和深蓝色)中结果
被填充以
a颜色只有一半的黑色像实际的笔画颜色。这是
在前面示例代码中使用1.0宽度行发生的情况。



要解决这个问题,你必须在你的路径创建非常精确。
知道一个1.0宽度线将延伸半个单位到路径的任一侧
,创建从(3.5,1)到(3.5,5)的路径导致
情况第三个图像 - 1.0行宽完全是
,并且正好填充单个像素垂直线。



I'm drawing line graphs on a canvas. The lines draw fine. The graph is scaled, every segment is drawn, color are ok, etc. My only problem is visually the line width varies. It's almost like the nib of a caligraphy pen. If the stroke is upward the line is thin, if the stroke is horizontal, the line is thicker.

My line thickness is constant, and my strokeStyle is set to black. I don't see any other properties of the canvas that affect such a varying line width but there must be.

解决方案

Live Demo

My live demo basically just recreates what the MDN says. For even stroke widths you can use integers for coordinates, for odd stroke widths you want to use .5 to get crisp lines that fill the pixels correctly.

From MDN Article

If you consider a path from (3,1) to (3,5) with a line thickness of 1.0, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code.

To fix this, you have to be very precise in your path creation. Knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image — the 1.0 line width ends up completely and precisely filling a single pixel vertical line.

这篇关于HTML5画布和线宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆