CSS 與 Canvas 都能畫圖形,但 Canvas 靠的是 JavaScript 程式邏輯,適合需要動態或大量運算的場景。本文用兩個實際範例,示範如何在網頁上分別繪製矩形與圓形。
不論畫什麼圖形,基本步驟都相同:取得 canvas 元素 → 取得 2D 上下文 → 設定樣式 → 進行繪製。若要畫較複雜的圖形,則改用路徑機制:開始建立路徑 → 建立圖形路徑 → 關閉路徑 → 描邊或填色。
以下程式在 body 的 onload 事件中同時觸發矩形與圓形的繪製函式:
<body onload="draw(), drawarc()">
繪製矩形:<canvas id="ca"></canvas><br />
繪製圓形:<canvas id="yuan"></canvas>
</body>
<script>
// 繪製矩形
function draw(){
var canvas = document.getElementById('ca');
if (canvas == null) return false;
var context = canvas.getContext('2d');
context.fillStyle = '#EEEFF'; // 底色
context.fillRect(0, 0, 400, 300); // 大矩形
context.fillStyle = 'red';
context.strokeStyle = 'blue'; // 邊框顏色
context.lineWidth = 1; // 邊框寬度
context.fillRect(50, 50, 100, 100); // 內側紅色矩形
context.strokeRect(50, 50, 100, 100);// 加上邊框
}
</script>
由於 Canvas 沒有現成的畫圓方法,我們改用 arc 畫圓弧,並搭配迴圈堆疊出多個半透明圓形,營造出層次感:
// 繪製圓形
function drawarc(){
var canvas2 = document.getElementById('yuan');
if (canvas2 == null) return false;
var context2 = canvas2.getContext('2d');
context2.fillStyle = '#EEEEEF';
context2.fillRect(0, 0, 400, 300);
for (var i = 0; i < 10; i++){
context2.beginPath(); // 開始路徑
context2.arc(i*25, i*25, i*10, 0, Math.PI*2, true); // 建立圓形路徑
context2.closePath(); // 關閉路徑
context2.fillStyle = 'rgba(255,0,0,0.25)'; // 半透明填色
context2.fill(); // 填色
}
}
把這兩個函式放進同一頁,就能看到矩形與由淡到濃堆疊而成的圓形效果。這正是 Canvas 的迷人所在:只要幾行程式碼,圖形便能依邏輯自由變化。