Skip to content

Instantly share code, notes, and snippets.

@hoadh
Created April 11, 2025 14:36
Show Gist options
  • Save hoadh/8767566ed4a95770013bbc4020739138 to your computer and use it in GitHub Desktop.
Save hoadh/8767566ed4a95770013bbc4020739138 to your computer and use it in GitHub Desktop.
Hình chữ nhật
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="400" style="border:1px solid black"></canvas>
</body>
<script>
/*
Viết một lớp đối tượng Rectangle để mô tả hình chữ nhật, với các đặc tính sau:
Thuộc tính:
- Chiều dài (length - kiểu int).
- Chiều rộng (width - kiểu int).
Phương thức:
- Tính diện tích hình chữ nhật.
- Tính chu vi hình chữ nhật.
- Hiển thị trực quan hình chữ nhật bằng cách vẽ lên canvas.
*/
class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
getLength() {
return this.length;
}
getWidth() {
return this.width;
}
setLength(length) {
if (this.length > 0) {
this.length = length;
} else {
// Báo lỗi
}
}
setWidth(width) {
this.width = width;
}
getArea() {
return this.length * this.width;
}
getPerimeter() {
return (this.length + this.width) * 2;
}
showCanvas(x, y) {
let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
context.fillStyle = "red";
context.fillRect(x, y, this.length, this.width);
}
}
let chuNhat1 = new Rectangle(100, 50);
// let dienTich = chuNhat1.getArea();
// document.write(dienTich);
chuNhat1.showCanvas(50, 50);
let chuVi = chuNhat1.getPerimeter();
document.write("Chu vi của hình chữ nhật là: " + chuVi);
document.write("<br>");
chuNhat1.length = 200;
chuNhat1.width = 100;
chuVi = chuNhat1.getPerimeter();
document.write("Chu vi của hình chữ nhật sau khi thay đổi chiều dài và chiều rộng là: " + chuVi);
chuNhat1.showCanvas(50, 200);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment