
rect() 是 Canvas 2D API 创建矩形路径的方法,矩形的起点位置是 (x, y) ,尺寸为 width 和 height。矩形的4个点通过直线连接,子路径做为闭合的标签,所以你可以填充或者描边矩形。
在线示例
绘制 150*100 像素的矩形:
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() 方法的使用(大卫编程网 div.cn)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
</script> 
</body>
</html>测试看看 ‹/›浏览器兼容性
IEFirefoxOperaChromeSafari
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 rect() 方法。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
定义和用法
rect() 方法创建一个矩形。
提示:请使用 stroke() 或fill() 方法在画布上实际绘制矩形。
| JavaScript 语法: | context.rect(x,y,width,height); | 
|---|
参数值
| 参数 | 描述 | 
|---|---|
| x | 矩形左上角的 x 坐标。 | 
| y | 矩形左上角的 y 坐标。 | 
| width | 矩形的宽度,以像素计。 | 
| height | 矩形的高度,以像素计。 | 
在线示例
通过 rect() 方法来创建三个矩形:
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() 方法的使用(大卫编程网 div.cn)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.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> 
</body>
</html>测试看看 ‹/›