แอตทริบิวต์ width ของ <canvas> คืออะไร?
แอตทริบิวต์ width ของแท็ก <canvas> ใช้สำหรับ กำหนดความกว้างของ Canvas ในหน่วยพิกเซล (Pixels)** ค่าเริ่มต้นคือ 300px หากไม่ระบุ
ไวยากรณ์ (Syntax)
<canvas width="pixels_value"></canvas>
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="200" style="border:3px dashed yellow">
เบราวเซอร์ไม่รองรับ HTML5 Canvas
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF5655";
ctx.fillRect(100, 50, 60, 100);
</script>
</body>
</html>
คำอธิบาย
width="400"กำหนดความกว้าง Canvas = 400 พิกเซลheight="200"กำหนดความสูง Canvas = 200 พิกเซล- JavaScript ใช้
canvas.getContext("2d")เพื่อวาดรูป fillRect(100, 50, 60, 100)วาดสี่เหลี่ยมสีแดง ตำแหน่ง (100,50) กว้าง 60 สูง 100
จุดสำคัญมาก: Width Attribute vs CSS Width
| ประเภท | คำอธิบาย | ผลกระทบ |
|---|---|---|
width="400" (Attribute) | ความกว้างของ **Coordinate Space** (พื้นที่วาด) | ส่งผลต่อความละเอียด การวาด จำนวนพิกเซล |
style="width: 400px" (CSS) | ความกว้างของ **Element บนหน้าจอ** (Display Size) | แค่ขยาย/ย่อการแสดงผล (Scale) ไม่เปลี่ยนพิกเซล |
<!-- ถูกต้อง: ตั้ง Attribute และ CSS ให้ตรงกัน --> <canvas id="c" width="800" height="600" style="width: 800px; height: 600px;"></canvas> <!-- ผิด: Attribute เล็ก CSS ใหญ่ → รูปจะเบลอ (Stretched) --> <canvas id="c" width="300" height="150" style="width: 800px; height: 600px;"></canvas>
Responsive Canvas Pattern
function resizeCanvas() {
var canvas = document.getElementById('myCanvas');
// ตั้ง Attribute = ขนาดจริงของ Container
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// วาดใหม่...
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();