javascript - 无法在 Canvas 上绘制垂直虚线

标签 javascript html canvas html5-canvas

我正在使用以下 javascript 算法在 Canvas 上绘制虚线。此算法正确绘制水平线但无法绘制垂直线:

            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]);

最佳答案

当直线垂直时,dx = 0 导致斜率 = Infinity。如果您编写自己的破折号逻辑,那么您需要处理 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);
};

关于javascript - 无法在 Canvas 上绘制垂直虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37296443/

相关文章:

javascript - 在 firebase.push() 之后读取创建的 key 和数据

javascript - 如何获取当前范围内定义的所有变量的列表?

html - 无法在所有版本的 Internet Explorer 上正确查看表格元素和无序列表

javascript - 重置变换: rotate() without invoking -webkit-transition: style

javascript - 调整 Canvas 上图像大小的问题

javascript - Titanium:Android设备上的数据加解密技术

javascript - 页面上jquery元素加载效果

javascript - 使用 Javascript 阻止 HTML 下拉框中的某些选项

c# - 使用控件 asp.net 动态填充 <td>

javascript - 如何在图像上添加可编辑的文本字段?