在 Canvas 普及之前,要在網頁上畫一個填色的矩形,最直覺的做法就是「用一個單格表格,指定它的背景色與寬高,再用絕對定位放到想去的位置」。這個技巧雖然樸素,卻很能說明 JavaScript 操作 DOM 與樣式的基本功。
<html>
<head>
<title>Javascript 畫矩形</title>
<script type="text/javascript">
// 傳入座標、寬高與顏色,輸出一個有背景色的表格
function drawFilledRect(x, y, w, h, color) {
document.write(
"<table border='0' cellspacing='0' cellpadding='0'>" +
"<tr><td style='position: absolute;" +
" left: " + x + ";" +
" top: " + y + ";" +
" background-color: " + color + ";'" +
" width=" + w + " height=" + h + ">" +
"</td></tr>" +
"</table>"
);
}
</script>
</head>
<body>
<script type="text/javascript">
drawFilledRect(20, 80, 100, 100, "red");
drawFilledRect(20, 180, 100, 100, "lime");
</script>
</body>
</html>
呼叫兩次,就能在頁面上畫出上下並排的紅色與綠色方塊。
關鍵是 position: absolute 搭配 left 與 top。表格本身在文件流中會佔位,但一旦設為絕對定位,它就脫離正常的排版,改用座標系統來定位——這才使得「指定 x, y 就能畫在該處」成立。
cellspacing="0" cellpadding="0" 與 border="0" 則是為了消除表格預設的邊框間距與內距,否則你看到的會是一個有白邊的方塊,尺寸也對不上。
今天要畫矩形,有兩個更好的選擇。
<style>
.rect {
position: absolute;
width: 100px;
height: 100px;
}
</style>
<script>
function drawRect(x, y, w, h, color) {
var div = document.createElement('div');
div.className = 'rect';
div.style.cssText =
'left:' + x + 'px;' +
'top:' + y + 'px;' +
'width:' + w + 'px;' +
'height:' + h + 'px;' +
'background:' + color;
document.body.appendChild(div);
}
drawRect(20, 80, 100, 100, 'red');
drawRect(20, 180, 100, 100, 'lime');
</script>
<canvas id="cv" width="400" height="300"></canvas>
<script>
var ctx = document.getElementById('cv').getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(20, 80, 100, 100);
ctx.fillStyle = 'lime';
ctx.fillRect(20, 180, 100, 100);
</script>
因為理解它,你才明白幾件事:position: absolute 如何讓元素脫離排版流、表格的 spacing 與 padding 為什麼會破壞尺寸計算,以及 document.write 為什麼在現代開發中被視為禁忌(它會在頁面載入完成後清空整個文件)。
三個方案對比很明顯:div 方案語意清楚、易於附加事件與動畫;Canvas 方案效能最好,適合大量圖形;而表格方案除了「用來理解舊程式碼」之外,已經沒有使用理由。