DIV CSS 佈局教程網

用 JS + HTML5 Canvas 繪製圓形
編輯:關於JavaScript     

HTML5 的 canvas 元素搭配 JavaScript,可以在頁面上直接作圖。繪製圓形只需要 arc() 這一個方法。

完整程式碼

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
</canvas>

<script type="text/javascript">
var c   = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
</body>
</html>

arc() 的參數拆解

ctx.arc(x, y, radius, startAngle, endAngle[, anticlockwise])
  • x, y:圓心座標(相對 canvas 左上角)
  • radius:半徑
  • startAngle / endAngle:起始角與結束角,以弧度為單位。一整圈是 2 * Math.PI
  • anticlockwise:是否逆時針繪製,預設 false(順時針)

因此 arc(95, 50, 40, 0, 2*Math.PI) 就是「圓心在 (95, 50)、半徑 40 的完整圓」。

beginPath 為什麼不能省

beginPath() 的作用是開啟一個新的路徑。若省略,這段弧線會跟前一個路徑連在一起,畫出來就多了一條莫名的線。養成「每畫一個新圖形就先 beginPath()」的習慣,能省下很多除錯時間。

stroke 與 fill 的差別

ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.fillStyle   = '#4caf50';
ctx.fill();     // 填滿內部
ctx.lineWidth   = 2;
ctx.strokeStyle = '#333';
ctx.stroke();   // 描邊

只呼叫 stroke() 得到空心圓,加上 fill() 才是實心圓。

延伸變化

// 半圓:0 到 PI
ctx.beginPath();
ctx.arc(60, 50, 40, 0, Math.PI);
ctx.stroke();

// 扇形(餅圖的基礎):圓心 → 弧線 → 閉合
ctx.beginPath();
ctx.moveTo(100, 50);
ctx.arc(100, 50, 40, 0, Math.PI / 2);
ctx.closePath();
ctx.fill();

掌握角度與弧度的換算(弧度 = 度數 × Math.PI / 180)之後,畫圓、扇形、圓角矩形都只是同一套語法的變形。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved