如下图,三角形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>
实现效果如下图: