The following code in the orthodox HTML5 Canvas
ctx. lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke();
The line drawn as a result of the operation is not a line with a width of one pixel
It feels so thick. It is very different from the various line drawing effects often seen on the web version
Same, didn’t HTML5 Canvas think of doing it better?
In fact, the fundamental reason is that the drawing of Canvas does not start from the middle
but from 0 to 1, not from 0.5 to 1 0 ~0.5 drawing method, so
causes the fade to be at the edge and the line looks very wide.
There are two solutions, one is the dislocation covering method, and the other is the center
translation (0.5, 0.5). The implementation code is as follows:
Dislocation coverage method I have wrapped it into a function of the original context
/**
*
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 center translation method 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();
Pay special attention to ensure that all your coordinate points are integers, otherwise HTML5 will Automatically implementing edge anti-aliasing
will cause one of your pixel straight lines to look thicker.
Operation effect:
How does it look now? This is a little trick for HTML5 Canvas line drawing.
Please give it a thumbs up if it sounds good.