Skip to content Skip to sidebar Skip to footer

Not Able To Draw Vertical Dashedline On Canvas

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 = func

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

Post a Comment for "Not Able To Draw Vertical Dashedline On Canvas"