How to draw dotted lines and html5canvas dotted lines in HTML5 canvas
The dotted line can also be seen as a solid line of the segment, while the solid line uses context. moveTo (x, y); context. lineTo (x2, y2); context. stroke ();
Then we can use the basic method of context to implement the implementation principle of the dotted line, as follows:
Var context = document. getElementById ('canvas '). getContext ('2d '); // evaluate the diagonal edge length function getBeveling (x, y) {return Math. sqrt (Math. pow (x, 2) + Math. pow (y, 2);} function drawDashLine (context, x1, y1, x2, y2, dashLen) {dashLen = dashLen === undefined? 5: dashLen; // obtain the total length of the Oblique Edge var beveling = getBeveling (x2-x1, y2-y1); // calculate the number of line segments var num = Math. floor (beveling/dashLen); for (var I = 0; I <num; I ++) {context [I % 2 = 0? 'Moveto ': 'line'] (x1 + (x2-x1)/num * I, y1 + (y2-y1)/num * I);} context. stroke ();} drawDashLine (context, 50,50, 300,180, 5 );
The results are as follows: