เมธอด fillRect() ของ Canvas คืออะไร?
เมธอด fillRect() ของ HTML Canvas ใช้สำหรับ วาดและทาสีสี่เหลี่ยมผืนผ้าในคำสั่งเดียว** สีเริ่มต้นคือสีดำ (#000000) ไม่ต้องใช้ beginPath() หรือ fill() แยก
ไวยากรณ์ (Syntax)
ctx.fillRect(x, y, width, height);
พารามิเตอร์
- x: พิกัด X มุมซ้ายบน
- y: พิกัด Y มุมซ้ายบน
- width: ความกว้าง
- height: ความสูง
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="350" style="border:2px solid orange;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// ทาสีพื้นหลังสีน้ำเงินเต็ม Canvas
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 500, 350);
// ล้างพื้นที่ตรงกลาง (ทำให้โปร่งใส)
ctx.clearRect(250, 100, 50, 100);
</script>
</body>
</html>
ผลลัพธ์
Canvas สีน้ำเงินเต็มจอ มีช่องว่างโปร่งใสสี่เหลี่ยมอยู่ตรงกลาง (x=250, y=100, w=50, h=100)
ความแตกต่าง fillRect() vs rect() + fill()
| เมธอด | ขั้นตอน | เหมาะสำหรับ |
|---|---|---|
fillRect(x,y,w,h) | คำสั่งเดียว วาดและทาเสร็จ | สี่เหลี่ยมเดี่ยว เร็ว สะดวก |
rect() + fill() | สร้าง path → ตั้ง fillStyle → fill() | Path 複雜, รวมหลายรูป, clip() |
เมธอดสี่เหลี่ยมครบชุด
fillRect(x, y, w, h)- ทาสีเต็มstrokeRect(x, y, w, h)- วาดขอบเท่านั้นclearRect(x, y, w, h)- ล้างพิกเซล (โปร่งใส)rect(x, y, w, h)- สร้าง path สี่เหลี่ยม (ต้อง fill/stroke ต่อ)