矩形是 Canvas 中最基礎的幾何圖形之一。在 Canvas 中,繪製矩形主要有三種內建方法:填充(fillRect)、描邊(strokeRect)以及清除(clearRect)。當然,我們也可以透過「路徑」來描繪包括矩形在內的各種圖形。
fillRect(x, y, width, height):繪製一個從 (x, y) 起始、寬為 width、高為 height 的實心矩形。strokeRect(x, y, width, height):繪製一個從 (x, y) 起始、寬為 width、高為 height 的矩形框。其樣式會依目前設定的 strokeStyle、lineWidth、lineJoin 與 miterLimit 屬性而有所不同。clearRect(x, y, width, height):清除從 (x, y) 起始、寬為 width、高為 height 的矩形區域,使其完全透明。在呼叫上述方法繪製之前,通常需要先設定填充色與描邊色。最基本的設定方式是使用 24 位色(以 16 進位字串表示):
context.fillStyle = "#000000";
context.strokeStyle = "#ff00ff";
在下面的完整示例中,填充色設為黑色,描邊色設為紫色:
function drawScreen() {
context.fillStyle = "#000000";
context.strokeStyle = "#ff00ff";
context.lineWidth = 2;
context.fillRect(10, 10, 40, 40); // 實心矩形
context.strokeRect(0, 0, 60, 60); // 矩形框
context.clearRect(20, 20, 20, 20); // 清除中央區域
}
透過這三個方法的組合,就能靈活地堆疊、覆蓋與清除畫布上的內容,是後續複雜繪圖的基礎。