Canvas rect() 方法
示例
繪製一個 150*100 畫素的矩形
JavaScript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();
自己動手試一試 »
描述
rect()
方法將一個矩形新增到路徑。
語法
context.rect(x, y, width, height) |
引數值
引數 | 描述 | 試一試 |
---|---|---|
x | 矩形左上角的 x 座標 | 試一試 » |
y | 矩形左上角的 y 座標 | 試一試 » |
width | 矩形的寬度(以畫素為單位) | 試一試 » |
height | 矩形的高度(以畫素為單位) | 試一試 » |
返回值
無 |
更多示例
示例
使用 rect() 方法建立三個矩形
JavaScript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 紅色矩形
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();
// 綠色矩形
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();
// 藍色矩形
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 150, 80);
ctx.stroke();
自己動手試一試 »
瀏覽器支援
<canvas>
元素是 HTML5 標準(2014)。
rect()
在所有現代瀏覽器中都受支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |
❮ Canvas 參考