How to use HTML5 Canvas Line drawing technique to draw a thin Line with Pixel width
How to use HTML5 Canvas line drawing skills to draw a thin line of pixel width, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
The code in the orthodox HTML5 Canvas is as follows
The code is as follows:
Ctx.lineWidth = 1
Ctx.beginPath ()
Ctx.moveTo (10,100)
Ctx.lineTo (300100)
Ctx.stroke ()
The result of the run is not a line with a pixel width.
Feel how thick ah, with the often seen web version of a variety of drawing line effect
It's very different. Didn't HTML5 Canvas think of doing better?
In fact, the fundamental reason is that the drawing of Canvas does not start from the middle.
It is drawn from 0 to 1, not from 0. 5 to 1 + 0. 5, so
Causes the fade to be at the edge and the line appears to be very wide.
There are two solutions, one is the dislocation coverage method, the other is the center
Translate (0.5, 0.5). The implementation code is as follows:
The misplaced covering method I have packaged as 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 of 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 (300100)
Ctx.stroke ()
Ctx.restore ()
Pay special attention to make sure that all your coordinate points are integers, otherwise HTML5 will automatically achieve edge anti-aliasing
It also causes one of your pixel lines to look thicker.
Running effect:
How does it work now? this is a little trick of HTML5 Canvas to draw lines.
I think it's good. Please take it.
After reading the above, have you mastered how to use HTML5 Canvas line drawing skills to draw a thin line with a pixel width? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!