Not able to draw vertical dashedline on canvas

此生再无相见时 提交于 2021-01-27 13:23:00

问题


I am using following javascript algorithm to draw dashed line on canvas. this algo draws horizontal line correctly but unable to draw vertical line:

            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();
        };

following Points used for testing vertical line draw:

  g.dashedLine(157, 117, 157,153, [10, 5]);

following Points used for testing horizontal line draw: g.dashedLine(157, 117, 160,157, [10, 5]);


回答1:


When the line is vertical, dx = 0 which leads to slope = Infinity. If you write your own dash logic then you need to handle the special case where dx = 0 (or very near 0). In this special case you would have to work with the inverse slope (i.e. dx / dy) and yStep (instead of xStep).

A bigger question is why are you writing your own dash logic. Canvas has built-in support for dashed lines. Call setLineDash() function to set the dash pattern. Restore the previous dash pattern when done. For example...

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


来源:https://stackoverflow.com/questions/37296443/not-able-to-draw-vertical-dashedline-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!