Canvas 提供 fillRect() 可直接繪製填滿的矩形。只要指定 x、y 座標與寬高,即可在畫布上產生方塊。
const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');
ctx.fillStyle = '#FF0000';
ctx.fillRect(0, 0, 150, 75);
fillStyle 決定填滿顏色,fillRect 的四個參數分別是左上角 x、y 與寬、高。若只需要外框,可使用 strokeRect()。