var context=document.getElementById("canvas").getContext("2d");
function drawDashedLine(context,x1,y1,x2,y2,dashlength){
dashlength=dashlength===undefined?5:dashlength;
var deltaX=x2-x1; //一条直角边的长
var deltay=y2-y1; //另一条指教边的长
var numDashes=Math.floor(
Math.sqrt(deltaX*deltaX+deltay*deltay)/dashlength //Math.sqrt返回一个数的平方根 dashlength虚线每个点的长度
)
var everydashLength_x=deltaX/numDashes //确定X轴每条虚线点的起始点
var everydashLength_y=deltay/numDashes //确定Y轴每条虚线点的起始点
for(var i=0;i<numDashes;i++){
context[i%2===0?'moveTo':"lineTo"]
(x1+everydashLength_x*i,y1+everydashLength_y*i)
}
context.stroke()
}
context.lineWidth=3
context.strokeStyle="blue"
drawDashedLine(context,20,20,context.canvas.width-20,20,20)