在Html5中,从(0.5,0)到(0.5,600)绘制以在画布上获得1像素粗线. 0.5很奇怪?

前端之家收集整理的这篇文章主要介绍了在Html5中,从(0.5,0)到(0.5,600)绘制以在画布上获得1像素粗线. 0.5很奇怪?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在读一本关于Html5和关于画布的书,以下代码生成1像素粗线…它使用0.5作为坐标.如果将其更改为0或10或某个整数,则这些线将为灰色,并且为2像素厚.这是为什么?这是我最近看到的最奇怪的事情……在Apple或Win32 API之前的所有编程,它们都是整数坐标.
<!DOCTYPE html>

<body>
<canvas id="c" width="800" height="600"></canvas>
</body>

<script>

var c_canvas = document.getElementById("c")
var context = c_canvas.getContext("2d")

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x,0)
  context.lineTo(x,375)
}
context.strokeStyle = "#000"
context.stroke()


</script>

另一个奇怪的事情是,要获得1像素乘1像素的黑点,我必须在x上绘制0.5,但是使用整数表示y

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x,1)
}

如果我使用以下内容,那么我会得到一个灰色的“更长点”

for (x = 0.5; x < 500; x += 10) {
  context.moveTo(x,0.5)
  context.lineTo(x,1.5)
}

解决方法

谢谢MiKy.我还找到了一些解释:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors#A_lineWidth_example

这是相关内容

Obtaining crisp lines requires understanding how paths are stroked. In@H_502_22@ the images below,the grid represents the canvas coordinate grid. The@H_502_22@ squares between gridlines are actual on-screen pixels. In the first@H_502_22@ grid image below,a rectangle from (2,1) to (5,5) is filled. The@H_502_22@ entire area between them (light red) falls on pixel boundaries,so the@H_502_22@ resulting filled rectangle will have crisp edges.

If you consider a path from (3,1) to (3,5) with a line thickness of@H_502_22@ 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@H_502_22@ either side of the path. An approximation of this has to be rendered,@H_502_22@ which means that those pixels being only partially shaded,and results@H_502_22@ in the entire area (the light blue and dark blue) being filled in with@H_502_22@ a color only half as dark as the actual stroke color. This is what@H_502_22@ 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相关文章