Javascript 无法在画布上绘制垂直虚线
我使用以下javascript算法在画布上绘制虚线。此算法正确绘制水平线,但无法绘制垂直线:Javascript 无法在画布上绘制垂直虚线,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,我使用以下javascript算法在画布上绘制虚线。此算法正确绘制水平线,但无法绘制垂直线: g.dashedLine = function (x, y, x2, y2, dashArray) { this.beginPath(); this.lineWidth = "2"; if (!dashArray) dashArray = [10, 5];
g.dashedLine = function (x, y, x2, y2, dashArray) {
this.beginPath();
this.lineWidth = "2";
if (!dashArray)
dashArray = [10, 5];
if (dashLength == 0)
dashLength = 0.001; // Hack for Safari
var dashCount = dashArray.length;
this.moveTo(x, y);
var dx = (x2 - x);
var dy = (y2 - y);
var slope = dy / dx;
var distRemaining = Math.sqrt(dx * dx + dy * dy);
var dashIndex = 0;
var draw = true;
while (distRemaining >= 0.1) {
var dashLength = dashArray[(dashIndex++) % dashCount];
if (dashLength > distRemaining)
dashLength = distRemaining;
var xStep = Math.sqrt((dashLength * dashLength) / (1 + slope * slope));
if (x < x2) {
x += xStep;
y += slope * xStep;
}
else {
x -= xStep;
y -= slope * xStep;
}
if (draw) {
this.lineTo(x, y);
}
else {
this.moveTo(x, y);
}
distRemaining -= dashLength;
draw = !draw;
}
this.stroke();
this.closePath();
};
用于测试水平线绘制的以下点:
g、 虚线(157171160157[10,5]) 直线垂直时,dx=0,导致斜率=无穷大。如果编写自己的破折号逻辑,则需要处理dx=0(或非常接近0)的特殊情况。在这种特殊情况下,您必须使用反向斜率(即dx/dy)和yStep(而不是xStep) 一个更大的问题是你为什么要写自己的破折号逻辑。画布内置了对虚线的支持。调用setLineDash()函数设置破折号图案。完成后恢复上一个破折号图案。例如
g.dashedLine = function (x, y, x2, y2, dashArray) {
this.beginPath();
this.lineWidth = "2";
if (!dashArray)
dashArray = [10, 5];
var prevDashArray = this.getLineDash();
this.setLineDash(dashArray);
this.moveTo(x, y);
this.lineTo(x2, y2);
this.stroke();
this.closePath();
this.setLineDash(prevDashArray);
};
当直线垂直时,dx=0,这导致斜率=无穷大。如果编写自己的破折号逻辑,则需要处理dx=0(或非常接近0)的特殊情况。在这种特殊情况下,您必须使用反向斜率(即dx/dy)和yStep(而不是xStep) 一个更大的问题是你为什么要写自己的破折号逻辑。画布内置了对虚线的支持。调用setLineDash()函数设置破折号图案。完成后恢复上一个破折号图案。例如
g.dashedLine = function (x, y, x2, y2, dashArray) {
this.beginPath();
this.lineWidth = "2";
if (!dashArray)
dashArray = [10, 5];
var prevDashArray = this.getLineDash();
this.setLineDash(dashArray);
this.moveTo(x, y);
this.lineTo(x2, y2);
this.stroke();
this.closePath();
this.setLineDash(prevDashArray);
};