Home  >  Article  >  Web Front-end  >  HTML5 Canvas line drawing skills - drawing a thin line one pixel wide_html5 tutorial skills

HTML5 Canvas line drawing skills - drawing a thin line one pixel wide_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:49:052014browse

The following code in the orthodox HTML5 Canvas

Copy the code
The code is as follows:

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

Copy code
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 center translation method code is as follows:

Copy the code
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();

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn