Phương thức HTML canvas direct ()

❮ Tham chiếu HTML Canvas

Thí dụ

Vẽ hình chữ nhật 150 * 100 pixel:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();

Hỗ trợ trình duyệt

Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ phương pháp này.

Method
rect() Yes 9.0 Yes Yes Yes

Định nghĩa và Cách sử dụng

Phương thức direct () tạo ra một hình chữ nhật.

Mẹo: Sử dụng phương thức stroke () hoặc fill () để thực sự vẽ hình chữ nhật trên canvas.

Cú pháp JavaScript: ngữ cảnh .rect ( x, y, width, height );

Giá trị tham số

Parameter Description Play it
x The x-coordinate of the upper-left corner of the rectangle
y The y-coordinate of the upper-left corner of the rectangle
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels

Các ví dụ khác

Thí dụ

Tạo ba hình chữ nhật bằng phương thức direct ():

Yourbrowserdoesnotsupportthecanvastag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

// Green rectangle
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();

// Blue rectangle
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 150, 80);
ctx.stroke();


❮ Tham chiếu HTML Canvas