The dashed line can also be seen as a segment of the solid lines, while the solid line is the use of Context.moveto (x, y); Context.lineto (x2,y2); Context.stroke ();
Then we can use the basic method of the context to complete the implementation of the dashed line principle, as follows:
var context = document.getElementById (' canvas '). GetContext (' 2d ');//Seek hypotenuse 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;//Gets the total length of the hypotenuse var beveling = Getbeveling (x2-x1,y2-y1);//Calculate how many segments var num = Math.floor (Beveling/dashlen); for (var i = 0; i < num; i++) {context[i%2 = = 2} ' MoveTo ': ' LineTo ' (x1+ (x2-x1)/num*i,y1+ (y2-y1)/num*i);} Context.stroke ();} Drawdashline (context,50,50,300,180,5);
The results are shown below:
How to draw dashed lines in HTML5 canvas