DIV CSS 佈局教程網

用 JS + HTML5 Canvas 繪製矩形:fillRect 與 strokeRect
編輯:關於JavaScript     

矩形是 Canvas 裡最基礎的圖形,而且內建了專用方法,不需要像圓形那樣自己 beginPath。

完整程式碼

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
  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.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
</script>
</body>
</html>

兩個矩形方法

ctx.fillRect(x, y, width, height)     // 填滿的矩形
ctx.strokeRect(x, y, width, height)   // 只有外框
ctx.clearRect(x, y, width, height)    // 清空指定區域(變透明)

四個參數分別是左上角 x 座標、y 座標、寬與高。範例中的 fillRect(0, 0, 150, 75) 就是在原點畫一個 150×75 的紅色方塊。

配色與線條樣式

// 填色
ctx.fillStyle = 'rgba(76, 175, 80, 0.6)';   // 支援 RGBA 透明度
ctx.fillRect(10, 10, 60, 40);

// 外框
ctx.strokeStyle  = '#2196f3';
ctx.lineWidth    = 4;
ctx.strokeRect(80, 10, 60, 40);

要注意 strokeRect 的線條是以路徑為中心向外向外各一半,因此線寬為 4 時,實際視覺邊界會超出宣告的座標 2px。若要求像素級精準對齊(例如畫格線),建議把座標設為半像素值或線寬設為奇數。

clearRect 的常見用途

function animate() {
  ctx.clearRect(0, 0, c.width, c.height); // 每幀先清乾淨,避免殘影
  // ... 重新繪製這一幀的內容
  requestAnimationFrame(animate);
}

做動畫時,「每幀清空 → 重畫」是最基本的骨架。

延伸:用矩形拼出圖形化介面

把 fillRect 與 clearRect 混合使用,就能做出長條圖、進度條、 heatmap 等元件。若需要圓角矩形,Canvas 目前提供了 ctx.roundRect(x, y, w, h, r)(較新的瀏覽器支援),舊環境則可用 arcTo() 自行拼出。

ctx.beginPath();
ctx.roundRect(10, 10, 120, 50, 8);
ctx.fill();
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved