The last canvas Line Painting tutorial
The last time we talked about canvas, sometimes one pixel lines may be blurred and seem wider, for example:
This line is obviously not what we want.
This articleArticleThe purpose is to find out the principle and solve it.
Everyone knows that the minimum display size on the screen is 1 pixel. Although something smaller than 1 pixel may not be displayed, the computer will try to draw it.
In fact, pixels are also a unit after all. What would happen if we enlarged the canvas to a large enough size to clearly view each pixel? It looks like this:
Each pixel has a starting and ending range, and their rangeStarting from left, crossing 1 pixel to right.
If we followStart and end ranges of pixelsThen we will surely get a very standard line. As follows:
Unfortunately, canvas's line drawing method is different. As we have already said in the previous article, each line of canvas has an infinitely fine"Midline", The width of the line is extended from the midline to both sides. If we still draw a line from 2nd pixels, then the lineMidlineIt's up to 2nd pixels.Start PointAnd then we start to draw the picture. The problem is that the canvas line is extended to both sides in the midline rather than to a certain side (for example, if it is only extended to the right side, then our problem is no longer a problem.) After the extension, our line is actually like this:
Now there is another problem: the computer does not allow images smaller than 1px, so he made a compromise:The two pixels are drawn..
Therefore, the line of 1px is a line that looks 2px wide.
Cause of failure: line in the canvas alignment the midline with the starting point of the pixel, rather than the middle point of the pixel.
So how can we solve this problem? Maybe someone has already thought of it: since the two start points are different, let's make their start points the same!
Let's align the midline of the line with the middle point of the pixel!
The middle point of the pixel is very easy to find, such as the middle point of 2nd pixels, according to the graph interpretation is the location of 1.5 pixels, then the middle point of X pixel is (x-0.5) PX.
Of course, in less rigorous scenarios, you can use X + 0.5.
Now let's try our research results on canvas.
1CTX. moveTo (100.5, 100.5);2CTX. lineto (200.5, 100.5);3CTX. lineto (200.5, 200.5);4CTX. lineto (100.5, 200.5);5CTX. lineto (100.5, 100.5);6 CTX. closepath ();7CTX. linewidth = 1;8CTX. strokestyle = 'rgba (255,0, 0, 0.5 )';9CTX. Stroke ();
Does it look right?
However, it seems that we are very entangled when we draw a line. Do we need to add this depressing 0.5 every time? Of course not, because most of the time we use variables to save the value, we don't need to add 0.5 to each value.
AndLinewidth> 1 lineWe don't need to worry about it either: this problem is most obvious only when the line width is 1 px.