HTML canvas rect () method
Examples
Draw a rectangle 150 * 100 pixels:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
try it"
Browser Support
Internet Explorer 9, Firefox, Opera, Chrome and Safari support rect () method.
Note: 8 and earlier versions of Internet Explorer do not support the <canvas> element.
Definition and Usage
rect () method to create a rectangle.
Tip: Use the stroke () or fill () method on the canvas to actually draw the rectangle.
JavaScript syntax: | context .rect (x, y, width, height); |
---|
Parameter Value
参数 | 描述 |
---|---|
x | 矩形左上角的 x 坐标。 |
y | 矩形左上角的 y 坐标。 |
width | 矩形的宽度,以像素计。 |
height | 矩形的高度,以像素计。 |
More examples
Examples
By rect () method to create three rectangles:
JavaScript:
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();
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();
try it"