无法在画布上绘制垂直虚线

3

我正在使用以下JavaScript算法在画布上绘制虚线。该算法可以正确地绘制水平线,但无法绘制垂直线:

            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.dashedLine(157, 117, 157,153, [10, 5]);

以下是用于测试绘制水平线的代码: g.dashedLine(157, 117, 160,157, [10, 5]);

1个回答

2
当线条为垂直时,dx = 0,则导致斜率为无穷大。如果你自己编写虚线逻辑,则需要处理特殊情况,即当dx = 0(或非常接近0)时。在这种特殊情况下,您将不得不使用反斜率(即dx / dy)和yStep(而不是xStep)来处理。
更大的问题是,为什么要编写自己的虚线逻辑。Canvas内置支持虚线。调用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);
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接