2016-05-18 72 views
3

我正在使用以下javascript算法在畫布上繪製虛線。此算法中正確地但無法繪製水平線畫垂直線:無法在畫布上繪製垂直虛線

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

回答

2

當線是垂直的,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); 
};