HTML Canvas 矩形
HTML Canvas 矩形
在 canvas 中绘制矩形最常用的三种方法是:
rect()
方法fillRect()
方法strokeRect()
方法
rect() 方法
rect()
方法定义一个矩形。
rect()
方法具有以下参数:
参数 | 描述 |
---|---|
x | 矩形左上角的 x 坐标 |
y | 矩形左上角的 y 坐标 |
width | 矩形的宽度(以像素为单位) |
height | 矩形的高度(以像素为单位) |
示例
使用 rect()
定义一个 150*100 像素的矩形,从位置 (10,10) 开始。然后使用 stroke()
实际绘制矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.rect(10,10, 150,100);
ctx.stroke();
</script>
自己动手试一试 »
请注意,rect()
方法不会绘制矩形(它只定义它)。因此,您还需要使用 stroke()
方法(或 fill()
方法)来实际绘制它。
fillRect() 方法
fillRect()
方法绘制一个填充矩形。
fillRect()
方法具有以下参数:
参数 | 描述 |
---|---|
x | 矩形左上角的 x 坐标 |
y | 矩形左上角的 y 坐标 |
width | 矩形的宽度(以像素为单位) |
height | 矩形的高度(以像素为单位) |
填充颜色通过 fillStyle
属性指定。如果未设置 fillStyle
属性,则默认填充颜色为黑色。
示例
使用 fillRect()
绘制一个从位置 (10,10) 开始的填充 150*100 像素矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillRect(10,10, 150,100);
</script>
自己动手试一试 »
示例
使用 fillStyle
属性设置填充颜色。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "pink";
ctx.fillRect(10,10, 150,100);
</script>
自己动手试一试 »
strokeRect() 方法
strokeRect()
方法绘制一个带描边的(轮廓)矩形。
strokeRect()
方法具有以下参数:
参数 | 描述 |
---|---|
x | 矩形左上角的 x 坐标 |
y | 矩形左上角的 y 坐标 |
width | 矩形的宽度(以像素为单位) |
height | 矩形的高度(以像素为单位) |
描边颜色通过 strokeStyle
属性指定。如果未设置 strokeStyle
属性,则默认描边颜色为黑色。
示例
使用 strokeRect()
绘制一个从位置 (10,10) 开始的带描边的 150*100 像素矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeRect(10,10, 150,100);
</script>
自己动手试一试 »
示例
使用 strokeStyle
属性设置轮廓的颜色。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.strokeRect(10,10, 150,100);
</script>
自己动手试一试 »
更多示例
示例
使用 rect()
方法创建三个矩形。
<script>
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();
</script>
自己动手试一试 »
示例
使用 strokeRect()
方法,用更少的代码获得与上面相同的结果。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 红色矩形
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.strokeRect(5, 5, 290, 140);
// 绿色矩形
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.strokeRect(30, 30, 50, 50);
// 蓝色矩形
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.strokeRect(50, 50, 150, 80);
</script>
自己动手试一试 »