使用canvas绘制虚线

canvas自身的api里没有绘制虚线的功能, 本片记录使用canvas绘制虚线的方法.

正文

定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype.lineTo) {
CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, dashArray) {
if (!dashArray) dashArray = [5, 5];
var dashCount = dashArray.length;
this.moveTo(x, y);
var dx = (x2 - x), dy = (y2 - y);
var slope = dy / dx;
var distRemaining = Math.sqrt(dx * dx + dy * dy);
var dashIndex = 0, draw = true;
while (distRemaining >= 0.1 && dashIndex < 10000) {
var dashLength = dashArray[dashIndex++ % dashCount];
if (dashLength == 0) dashLength = 0.001; // Hack for Safari
if (dashLength > distRemaining) dashLength = distRemaining;
var xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
x += xStep
y += slope * xStep;
this[draw ? 'lineTo' : 'moveTo'](x, y);
distRemaining -= dashLength;
draw = !draw;
}
// Ensure that the last segment is closed for proper stroking
this.moveTo(0, 0);
}
}

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
function dashedLine(context, startX, startY, endX, endY) {
var canvas = document.getElementById(canvasID);
var cxt = context;
var dashes = [5,5];
cxt.lineWidth = "3";
cxt.lineCap = "round";
cxt.beginPath();
cxt.strokeStyle = 'blue';
//开始画虚线。
cxt.dashedLine(startX, startY, endX, endY, dashes);
cxt.closePath();
cxt.stroke();
}

示例:

1
2
3
4
5
6
7
8
   <canvas id='canvas' width="500" height="500"></canvas>
<script>
window.onload = function(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
dashedLine(context, 0 ,0, 200, 200);
}
</script>