HTML Canvas 矩形

實例

YourbrowserdoesnotsupporttheHTML5canvastag.

繪制一個 150*100 像素的矩形:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();

親自試一試

rect() 方法

rect() 方法向路徑添加一個矩形。

語法:

context.rect(x, y, width, height)
參數 描述
x 矩形左上角的 x 坐標。
y 矩形左上角的 y 坐標。
width 矩形的寬度,以像素為單位。
height 矩形的高度,以像素為單位。

更多實例

實例

使用 rect() 方法創建三個矩形:

Yourbrowserdoesnotsupportthecanvastag.

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();

親自試一試

另請參閱:

CodeW3C.com 的完整 Canvas 參考手冊