由於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>