2012-03-13 108 views
1

玩一個突破克隆,並希望做出圓角的通電。如何在Canvas中製作藥丸形狀? (基本上是圓角矩形)

有人能指出我正確的方向嗎?

謝謝!

+1

的重複[如何繪製一個圓角矩形的HTML畫布?](http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-上的html-帆布);請參閱[本答案](http://stackoverflow.com/a/7838871/405017)。下次,請首先在網站或網上搜索答案。 – Phrogz 2012-03-13 22:38:59

回答

3

你可以做什麼的顯示on this article by Juan Mendes

HTML:

<canvas id="rounded-rect" width="600" height="600"> 
    <!-- Insert fallback content here --> 
</canvas>​ 

的JavaScript:

CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius, fill, stroke) { 
    if (typeof stroke == "undefined") { 
     stroke = true; 
    } 
    if (typeof radius === "undefined") { 
     radius = 5; 
    } 
    this.beginPath(); 
    this.moveTo(x + radius, y); 
    this.lineTo(x + width - radius, y); 
    this.quadraticCurveTo(x + width, y, x + width, y + radius); 
    this.lineTo(x + width, y + height - radius); 
    this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); 
    this.lineTo(x + radius, y + height); 
    this.quadraticCurveTo(x, y + height, x, y + height - radius); 
    this.lineTo(x, y + radius); 
    this.quadraticCurveTo(x, y, x + radius, y); 
    this.closePath(); 
    if (stroke) { 
     this.stroke(stroke); 
    } 
    if (fill) { 
     this.fill(fill); 
    } 
}; 

// Now you can just call 
var ctx = document.getElementById("rounded-rect").getContext("2d"); 
// Manipulate it again 
ctx.strokeStyle = "#2d6"; 
ctx.fillStyle = "#abc"; 
ctx.roundRect(100, 200, 200, 100, 50, true); 

正如你可以在此JsFiddle

+0

謝謝!這很好! – 2012-03-14 04:23:01

4

一個簡單的方法就是用看quadraticCurveTo平滑角落

enter image description here

function roundRect(x0, y0, x1, y1, r, color) 
{ 
    var w = x1 - x0; 
    var h = y1 - y0; 
    if (r > w/2) r = w/2; 
    if (r > h/2) r = h/2; 
    ctx.beginPath(); 
    ctx.moveTo(x1 - r, y0); 
    ctx.quadraticCurveTo(x1, y0, x1, y0 + r); 
    ctx.lineTo(x1, y1-r); 
    ctx.quadraticCurveTo(x1, y1, x1 - r, y1); 
    ctx.lineTo(x0 + r, y1); 
    ctx.quadraticCurveTo(x0, y1, x0, y1 - r); 
    ctx.lineTo(x0, y0 + r); 
    ctx.quadraticCurveTo(x0, y0, x0 + r, y0); 
    ctx.closePath(); 
    ctx.fillStyle = color; 
    ctx.fill(); 
} 
+0

不錯的圖形,但使用'arcTo'要簡單得多,不是嗎? (正如我發現並鏈接到的重複問題所證明的那樣,當你大概寫出你的答案時)。 – Phrogz 2012-03-14 01:20:35

+0

@Phrogz:使用貝塞爾曲線使平凡具有各向異性舍入,並且四分之一圓和二次貝塞爾弧之間的差異是IMO小到足以在大多數情況下可以接受。在我看來,Canvas'arc/arcTo'的設計非常糟糕(我甚至在瀏覽器之間發現了兼容性問題):我通常使用'arc'來繪製整個圓。你是對的重複,但海事組織貝塞爾二次方式更適合這種用途。 – 6502 2012-03-14 06:40:50

相關問題