Draw a fine line with pixel width. When using HTML5Canvas to implement it, make sure that all your coordinate points are integers. Otherwise, HTML5 will automatically implement edge anti-aliasing, if you are interested, you can refer to the following code in the Orthodox HTML5 Canvas:
The Code is as follows:
Ctx. lineWidth = 1;
Ctx. beginPath ();
Ctx. moveTo (10,100 );
Ctx. lineTo (300,100 );
Ctx. stroke ();
The running result is not a line of pixel width.
I think it's so rough. I often see various online effects on Web pages.
Very different. Why didn't HTML5 Canvas do well?
In fact, the root cause is that Canvas is not drawn from the middle.
From 0 ~ 1, not from 0.5 ~ 1 + 0 ~ 0.5 of the drawing method, so
As a result, fade is on the edge and looks very wide.
There are two solutions: one is the dislocation coverage method and the other is the center
Translation (0.5, 0.5 ). The implementation code is as follows:
I have encapsulated the dislocation overwrite method into a function of the original context.
The Code is as follows:
/**
*
Draw one pixel line
* @ Param fromX
* @ Param formY
* @ Param toX
* @ Param toY
* @ Param backgroundColor-default is white
* @ Param vertical-boolean
*/
CanvasRenderingContext2D. prototype. onePixelLineTo = function (fromX, fromY, toX, toY, backgroundColor, vertical ){
Var currentStrokeStyle = this. strokeStyle;
This. beginPath ();
This. moveTo (fromX, fromY );
This. lineTo (toX, toY );
This. closePath ();
This. lineWidth = 2;
This. stroke ();
This. beginPath ();
If (vertical ){
This. moveTo (fromX + 1, fromY );
This. lineTo (toX + 1, toY );
} Else {
This. moveTo (fromX, fromY + 1 );
This. lineTo (toX, toY + 1 );
}
This. closePath ();
This. lineWidth = 2;
This. strokeStyle = backgroundColor;
This. stroke ();
This. strokeStyle = currentStrokeStyle;
};
The code for the center translation method is as follows:
The Code is as follows:
Ctx. save ();
Ctx. translate (0.5, 0.5 );
Ctx. lineWidth = 1;
Ctx. beginPath ();
Ctx. moveTo (10,100 );
Ctx. lineTo (300,100 );
Ctx. stroke ();
Ctx. restore ();
Make sure that all of your coordinate points are integers. Otherwise, HTML5 automatically implements edge anti-aliasing.
It also makes a straight pixel line look rough.
Running effect:
What is the effect now? This is a little trick for HTML5 Canvas to draw lines.
Think it's good. Please try it out.