คุณสมบัติ shadowColor ของ Canvas คืออะไร?
คุณสมบัติ shadowColor ของ HTML Canvas ใช้สำหรับ ตั้งค่าสีของเงา (Shadow Color)** สำหรับรูปทรงที่จะวาดต่อไป ค่าเริ่มต้นคือ #000000 (สีดำ)
ไวยากรณ์ (Syntax)
ctx.shadowColor = "color_value";
รองรับทุกรูปแบบ CSS Color: Named Color, Hex, RGB, RGBA, HSL, HSLA
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="600" height="350" style="border:2px solid orange;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.shadowBlur = 20; // ความเบลอของเงา
ctx.shadowColor = "gray"; // สีเงา
ctx.fillStyle = "blue"; // สีรูปทรง
ctx.fillRect(40, 40, 200, 250); // วาดสี่เหลี่ยมพร้อมเงา
</script>
</body>
</html>
ผลลัพธ์
สี่เหลี่ยมสีน้ำเงินพร้อมเงาสีเทาเบลอ รัศมี 20px
คุณสมบัติเงาครบชุด (Shadow Properties)
| คุณสมบัติ | คำอธิบาย | ค่าเริ่มต้น |
|---|---|---|
shadowColor | สีของเงา | #000000 |
shadowBlur | ระดับความเบลอ (ไม่มีหน่วย พิกเซล) | 0 (ไม่เบลอ) |
shadowOffsetX | ระยะห่างแนวนอนของเงา (พิกเซล) | 0 |
shadowOffsetY | ระยะห่างแนวตั้งของเงา (พิกเซล) | 0 |
ตัวอย่าง: เงาครบชุด
ctx.shadowOffsetX = 10; // เงาขยับขวา 10px ctx.shadowOffsetY = 10; // เงาขยับลง 10px ctx.shadowBlur = 15; // เบลอ 15px ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; // สีดำโปร่งใส 50% ctx.fillStyle = "red"; ctx.fillRect(50, 50, 150, 100);
จุดสำคัญ
- เงาจะแสดงได้ก็ต่อเมื่อ
shadowBlur > 0หรือshadowOffsetX/Y != 0 - เงาส่งผลต่อ
fillRect,strokeRect,fillText,strokeText,drawImage, Path drawing - ใช้
rgba()หรือhsla()เพื่อควบคุมความโปร่งใสของเงา - Performance: เงาเยอะ/Blur สูง อาจทำ Canvas ช้า