HTML Canvas 矩形
实例
绘制一个 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() 方法创建三个矩形:
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();