2.8.6_通过扩展CanvasRenderingContext2D来绘制虚线
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>通过扩展CanvasRenderingContext2D来绘制虚线</title>
<style>
body{
background: #eee;
}
#canvas{
background: #fff;
cursor: pointer;
margin-left: 10px;
margin-top: 10px;
box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
-webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
-moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
moveToFunction = CanvasRenderingContext2D.prototype.moveTo;
CanvasRenderingContext2D.prototype.lastMoveToLocation = {};
CanvasRenderingContext2D.prototype.moveTo = function(x,y){
moveToFunction.apply(context,[x,y]);
this.lastMoveToLocation.x = x;
this.lastMoveToLocation.y = y;
}
CanvasRenderingContext2D.prototype.dashedLineTo = function (x,y,dashLenth){
dashLenth = dashLenth ===undefined? 5:dashLenth;
var startX=this.lastMoveToLocation.x;
var startY = this.lastMoveToLocation.y;
var deltaX = x-startX;
var deltaY = y-startY;
var numDashes = Math.floor(Math.sqrt(deltaX*deltaX + deltaY*deltaY)/dashLenth);
for(var i=0;i<numDashes;i++){
this[i%2===0? 'moveTo':'lineTo'](startX+(deltaX/numDashes)*i,startY+(deltaY/numDashes)*i);
}
this.moveTo(x,y);
}
context.lineWidth = 3;
context.strokeStyle = 'blue';
context.moveTo(20,20);
context.d ashedLineTo(context.canvas.width-20,20);
context.dashedLineTo(context.canvas.width-20,context.canvas.height-20);
context.dashedLineTo(20,context.canvas.height-20);
context.dashedLineTo(20,20);
context.dashedLineTo(context.canvas.width-20,context.canvas.height-20);
context.stroke();
</script>
</html>