rect() 是 Canvas 2D API 創(chuàng)建矩形路徑的方法,矩形的起點(diǎn)位置是 (x, y) ,尺寸為 width 和 height。矩形的4個(gè)點(diǎn)通過(guò)直線連接,子路徑做為閉合的標(biāo)簽,所以你可以填充或者描邊矩形。
繪制 150*100 像素的矩形:
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() 方法的使用(菜鳥教程 cainiaoplus.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支持 HTML5 canvas 標(biāo)簽。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
</script>
</body>
</html>測(cè)試看看 ?/?IEFirefoxOperaChromeSafari
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 rect() 方法。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
rect() 方法創(chuàng)建一個(gè)矩形。
提示:請(qǐng)使用 stroke() 或fill() 方法在畫布上實(shí)際繪制矩形。
| JavaScript 語(yǔ)法: | context.rect(x,y,width,height); |
|---|
| 參數(shù) | 描述 |
|---|---|
| x | 矩形左上角的 x 坐標(biāo)。 |
| y | 矩形左上角的 y 坐標(biāo)。 |
| width | 矩形的寬度,以像素計(jì)。 |
| height | 矩形的高度,以像素計(jì)。 |
通過(guò) rect() 方法來(lái)創(chuàng)建三個(gè)矩形:
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() 方法的使用(菜鳥教程 cainiaoplus.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支持 HTML5 canvas 標(biāo)簽。
</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();
// 藍(lán)色矩形
ctx.beginPath();
ctx.lineWidth="10";
ctx.strokeStyle="blue";
ctx.rect(50,50,150,80);
ctx.stroke();
</script>
</body>
</html>測(cè)試看看 ?/?