HTML5 Canvas draws dotted line instances, html5canvas
This article mainly introduces the example of using HTML5 Canvas to draw dotted lines. HTML5 does not provide a dotted line method. This article is based on the method of Stack Overflow. For more information, see
HTML5 Canvas provides a lot of graphic rendering functions, but unfortunately, the Canvas API only provides the lineTo function, but does not provide a dotted line method. Such a design may cause great inconvenience. David Flanagan, author of The JavaScript authoritative guide, thinks that such a decision is problematic, especially when the standard modification and implementation are relatively simple ("... Something that is so trivial to add to the specification and so trivial to implement... I really think you're making a mistake here "-http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2007-May/011224.html ).
On Stack Overflow, Phrogz provides an implementation of its own dotted line (http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas), strictly speaking, which is an implementation of the dot line (p.s. I think the simplified version of Rod macdeskall on this page is better ). What should I do if I need to draw a dotted line (as shown in?
The following is my own implementation. It only supports horizontal and vertical dotted lines. You can refer to the Phrogz and Rod mac1_all methods to add the oblique line drawing function.
The Code is as follows:
Var canvasPrototype = window. CanvasRenderingContext2D & CanvasRenderingContext2D. prototype;
CanvasPrototype. dottedLine = function (x1, y1, x2, y2, interval ){
If (! Interval ){
Interval = 5;
}
Var isHorizontal = true;
If (x1 = x2 ){
IsHorizontal = false;
}
Var len = isHorizontal? X2-x1: y2-y1;
This. moveTo (x1, y1 );
Var progress = 0;
While (len & gt; progress ){
Progress + = interval;
If (progress & gt; len ){
Progress = len;
}
If (isHorizontal ){
This. moveTo (x1 + progress, y1 );
This. arc (x1 + progress, y1, 1, 0, 2 * Math. PI, true );
This. fill ();
} Else {
This. moveTo (x1, y1 + progress );
This. arc (x1, y1 + progress, 1, 0, 2 * Math. PI, true );
This. fill ();
}
}
}