<!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) }
解决方法
这是相关内容:
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.