Example Analysis of Canvas Line drawing skills in HTML5
This article mainly shows you the "example analysis of Canvas line-drawing skills in HTML5", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let me lead you to study and learn the "example analysis of Canvas line-drawing skills in HTML5".
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:
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.
The above is all the contents of the article "sample Analysis of Canvas Line drawing skills in HTML5". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!