Comment: Draw a thin line with a pixel width. When using HTML5 Canvas implementation, pay special attention to making sure that all your coordinate points are integers, otherwise HTML5 will automatically achieve edge anti-aliasing. Interested friends can see the effect diagram
The following code in the orthodox HTML5 Canvasctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300,100);
ctx.stroke();
The result of the operation is not a pixel-width line
How thick it feels, and it is as common as the web version of various line drawing effects
Very different, didn't you think HTML5 Canvas would do it better?
In fact, the fundamental reason is that the drawing of Canvas does not start from the middle.
Instead, it is drawn from 0 to 1, not from 0.5 to 1 + 0 to 0.5, so
This leads to the fade on the edge, and looks very wide in line.
There are two solutions, one is the misalignment coverage method, and the other is the center
Translation (0.5,0.5). The implementation code is as follows:
I have wrapped the misplaced overlay method into a function of the original context
/**
* <p> draw one pixel line </p>
* @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 central 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();
Be especially careful to make sure that all your coordinate points are integers, otherwise HTML5 will automatically implement edge antialiasing
This causes one of your pixels to look thicker.
Running effect:
What's the effect now? This is a tip for drawing lines in HTML5 Canvas
If you think it's good, please give it a try.