var context=document.getElementById("canvas").getContext("2d");
function drawDashedLine(context,x1,y1,x2,y2,dashlength){
dashlength=dashlength===undefined?5:dashlength;
var deltaX=x2-x1; //一條直角邊的長(zhǎng)
var deltay=y2-y1; //另一條指教邊的長(zhǎng)
var numDashes=Math.floor(
Math.sqrt(deltaX*deltaX+deltay*deltay)/dashlength //Math.sqrt返回一個(gè)數(shù)的平方根 dashlength虛線每個(gè)點(diǎn)的長(zhǎng)度
)
var everydashLength_x=deltaX/numDashes //確定X軸每條虛線點(diǎn)的起始點(diǎn)
var everydashLength_y=deltay/numDashes //確定Y軸每條虛線點(diǎn)的起始點(diǎn)
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)