2012-03-27 169 views
0

我正在爲canvascontext寫一些額外的drawfunction。下面的代碼應該允許用戶用虛線或法線繪製圓角矩形。這幾乎是完整的工作代碼,但在繪製結束時,在圓角處繪製了一條額外的線條(我包含了該問題的圖片)。請注意,只有在繪製矩形虛線時出現此問題,而其他版本則完美。圓角矩形虛線

if (window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype.lineTo){ 
     CanvasRenderingContext2D.prototype.dashedLine = function(pt1, pt2, dashLen) { 
       if (dashLen == undefined) dashLen = 6; 

       var dX = pt2.x - pt1.x; 
       var dY = pt2.y - pt1.y; 
       var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY)/dashLen); 
       var dashX = dX/dashes; 
       var dashY = dY/dashes; 

       var q = 0; 
       while (q++ < dashes) { 
       pt1.x += dashX; 
       pt1.y += dashY; 
       this[q % 2 == 0 ? 'moveTo' : 'lineTo'](pt1.x, pt1.y); 
       } 
       this[q % 2 == 0 ? 'moveTo' : 'lineTo'](pt2.x, pt2.y); 
      }; 
     CanvasRenderingContext2D.prototype.roundRectangle = function(pt1, pt2, pt3, pt4, dashed, dashLen) { 
       function line(ctx, x1, y1, x2, y2, dashed) { 
       if (dashed) ctx.dashedLine({x:x1, y:y1}, {x:x2, y:y2}); 
       else { 
        ctx.lineTo(x2,y2);} 
       } 
       var radius = 8; 
       this.beginPath(); 
       line(this, pt1.x + radius, pt1.y, pt2.x - radius, pt2.y, dashed); 
       this.quadraticCurveTo(pt2.x, pt2.y, pt2.x, pt2.y + radius); 
       line(this, pt2.x, pt2.y + radius, pt3.x, pt3.y - radius, dashed); 
       this.quadraticCurveTo(pt3.x, pt3.y, pt3.x - radius, pt3.y); 
       line(this, pt3.x - radius, pt3.y, pt4.x + radius, pt4.y, dashed); 
       this.quadraticCurveTo(pt4.x, pt4.y, pt4.x, pt4.y - radius); 
       line(this, pt4.x, pt4.y - radius, pt1.x, pt1.y + radius, dashed); 
       this.quadraticCurveTo(pt1.x, pt1.y, pt1.x + radius, pt1.y); 

       this.closePath(); 
       this.stroke(); 
       this.fill(); 
     } 

}

enter image description here

有誰知道什麼可以在這裏是什麼問題?

回答

1

this.closePath();行補充說,最後一段直線。只要刪除它。

此外,爲了獲得更好的結果,除去this.beginPath();線和添加以下一個代替:

this.moveTo(pt1.x + radius, pt1.y); 

檢查修改後的代碼:http://jsfiddle.net/W8b3e/

+0

感謝您解決這個問題,但我想添加填充選項,以便背景可以着色。當我這樣做時,只有二次曲線區域被着色,所以我需要這條路徑。我在這裏更改了代碼:http://jsfiddle.net/W8b3e/2/ – Consec 2012-03-28 12:13:21