html canvas 绘制圆角矩形
由于canvas没有直接绘制椭圆的方法,只能通过拼接的形式去绘制;
将椭圆拆解成6部分,两条横向和4个四分之一圆;
通过使用lineTo和arcTo这两个方法去进行拼接;
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas> <button onclick="myFunction()">尝试一下</button>
<script> function myFunction() { let c=document.getElementById("myCanvas"); let ctx=c.getContext("2d"); let createdEllipse = (ctx, x, y, w, h, color) => { let r = h / 2; // 圆半径 let l_w = Math.abs(w - h); // 线长度 ctx.beginPath(); ctx.moveTo(x+r, y); // 创建开始点 ctx.lineTo(x+r+l_w,y); // 创建水平线 ctx.arcTo(x+w,y,x+w,y+r,r); // 创建弧 ctx.arcTo(x+w,y+h,x+r+l_w,y+h,r); // 创建弧 ctx.lineTo(x+r,y+h); // 创建垂直线 ctx.arcTo(x,y+h,x,y+r,r); // 创建弧 ctx.arcTo(x,y,x+r,y,r); // 创建弧 ctx.strokeStyle = color; ctx.stroke(); ctx.clip(); ctx.fillStyle = color; ctx.fill(); ctx.restore(); ctx.closePath(); ctx.save(); } createdEllipse(ctx, 10, 10, 60, 20, '#000000'); } </script>