context.arcTo()
arcTo() 方法在畫布上創建介於兩個切線之間的弧/曲線。
JavaScript 語法: | context.arcTo(x1,y1,x2,y2,r); |
---|
參數描述
參數 | 描述 |
---|---|
x1 | 弧的起點的 x 坐標。 |
y1 | 弧的起點的 y 坐標。 |
x2 | 弧的終點的 x 坐標。 |
y2 | 弧的終點的 y 坐標。 |
r | 弧的半徑。 |
使用如下:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); // 創建開始點 ctx.lineTo(100,20); // 創建水平線 ctx.arcTo(150,20,150,70,50); // 創建弧 ctx.lineTo(150,120); // 創建垂直線 ctx.stroke(); // 繪制
上述代碼繪制效果如下:
起點A,先畫一條線AB,使用arcTo聲明另外一條線CD,那么BC和CD組成一個夾角,arcTo繪制半徑為50的圓弧,然后連接到E點
如果把創建弧的C點坐標改一下(150,0):ctx.arcTo(150,0,150,70,50);
如下圖看到因為半徑大,所以圓弧會撐開,圓弧的起點撐到了BC的線段的反向延長線上
我們把半徑改小到20,ctx.arcTo(150,0,150,70,20)
如下圖:
繪制圓角多邊形
理解了arcTo畫弧的邏輯,我們回到繪制圓角多邊形的話題
需求簡述如下圖,三角形ABC,我們繪制成圓角,頂點處是個圓弧。
知道多半形頂點坐標,利用canvas的api方法 arcTo()
就可以實現了。
一個繪制圓角多邊形簡單的實現:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8" /> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 7 <title>Document</title> 8 <style> 9 #canvas { 10 width: 400px; 11 height: 400px; 12 } 13 </style> 14 </head> 15 16 <body> 17 <canvas id="canvas" width="800" height="800"></canvas> 18 </body> 19 <script> 20 function draw() { 21 const p = [ 22 [15, 20], 23 [20, 200], 24 [200, 300], 25 [300, 100], 26 [200, 20], 27 ]; 28 const p1 = [ 29 [300,50], 30 [400,50], 31 [350,150] 32 ] 33 const canvas = document.getElementById("canvas"); 34 const ctx = canvas.getContext("2d"); 35 drawRect(p, 30, ctx); 36 drawRect(p1, 10, ctx); 37 } 38 39 function drawRect(p, radius, ctx) { 40 ctx.beginPath(); 41 const startPoint = [ 42 (p[0][0] + p[p.length - 1][0]) / 2, 43 (p[0][1] + p[p.length - 1][1]) / 2, 44 ]; 45 ctx.moveTo(...startPoint); 46 for (let i = 0; i < p.length; i++) { 47 if (i === p.length - 1) { 48 ctx.arcTo(...p[p.length - 1], ...p[0], radius); 49 } else { 50 ctx.arcTo(...p[i], ...p[i + 1], radius); 51 } 52 } 53 ctx.closePath(); 54 ctx.stroke(); 55 } 56 window.onload = function() { 57 draw(); 58 }; 59 </script> 60 61 </html>
實現效果如下圖: