Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML Canvas shadowBlur Property - ตั้งค่าความเบลอของเงา

คุณสมบัติ shadowBlur ของ Canvas 2D Context ใช้กำหนดระดับความเบลอ (blur level) ของเงา ค่าเริ่มต้นคือ 0 (ไม่มีการเบลอ คมชัด) ค่าที่มากขึ้น = เงาเบลอมากขึ้น (นุ่มนวลกว่า)

รูปแบบการใช้งาน

ctx.shadowBlur = number; // ค่าตัวเลข >= 0

คุณสมบัติเงาทั้งหมด (Shadow Properties)

คุณสมบัติ คำอธิบาย ค่าเริ่มต้น
shadowBlur ระดับความเบลอของเงา 0
shadowColor สีของเงา (CSS color string) "rgba(0,0,0,0)" (โปร่งใส)
shadowOffsetX ระยะห่างแนวนอนของเงา (px) 0
shadowOffsetY ระยะห่างแนวตั้งของเงา (px) 0

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body>
  <canvas id="shadowCanvas" width="600" height="350" style="border:2px solid orange;">
    เบราว์เซอร์ไม่รองรับ Canvas
  </canvas>
  
  <script>
    const canvas = document.getElementById('shadowCanvas');
    const ctx = canvas.getContext('2d');
    
    // สี่เหลี่ยมแรก - เงาเบลอปานกลาง สีดำ
    ctx.shadowBlur = 20;
    ctx.shadowColor = "black";
    ctx.shadowOffsetX = 10;
    ctx.shadowOffsetY = 10;
    ctx.fillStyle = "green";
    ctx.fillRect(40, 40, 100, 250);
    
    // สี่เหลี่ยมที่สอง - เงาเบลอมาก สีน้ำเงิน
    ctx.shadowBlur = 30;
    ctx.shadowColor = "blue";
    ctx.shadowOffsetX = 15;
    ctx.shadowOffsetY = 15;
    ctx.fillStyle = "orange";
    ctx.fillRect(200, 40, 200, 150);
    
    // สี่เหลี่ยมที่สาม - ไม่มีเงา (reset)
    ctx.shadowBlur = 0;
    ctx.shadowColor = "rgba(0,0,0,0)";
    ctx.fillStyle = "red";
    ctx.fillRect(450, 40, 100, 100);
  </script>
</body>
</html>

ผลการทำงาน (Output)

จะเห็นสี่เหลี่ยม 3 รูป:

  1. สีเขียว - มีเงาสีดำเบลอปานกลาง (blur 20)
  2. สีส้ม - มีเงาสีน้ำเงินเบลอมาก (blur 30)
  3. สีแดง - ไม่มีเงา (blur 0)

เคล็ดลับการใช้งาน

  • Performance: shadowBlur สูงมาก (มากกว่า 50) อาจทำให้ rendering ช้าลงในอุปกร์ที่อ่อน
  • Reset shadows: ตั้งค่า shadowBlur = 0 และ shadowColor = "transparent" ก่อนวาดสิ่งที่ไม่ต้องการเงา
  • ร่วมกับ save/restore: ใช้ ctx.save() และ ctx.restore() เพื่อจัดการสถานะเงาได้ง่ายขึ้น

ตัวอย่างใช้ save/restore

// วาดพร้อมเงา
ctx.save();
ctx.shadowBlur = 15;
ctx.shadowColor = "rgba(0,0,0,0.5)";
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100);
ctx.restore(); // คืนค่า shadow เป็นเดิม (0)

// วาดโดยไม่มีเงา
ctx.fillStyle = "red";
ctx.fillRect(130, 10, 100, 100);

กรณีใช้งานจริง

  • สร้างเอฟเฟกต์ความลึก (depth) สำหรับ UI elements
  • Game development - เงาตัวละคร/วัตถุ
  • Data visualization - แยกชุดข้อมูลด้วยเงา
  • Text effects - ข้อความมีเงา (textShadow ใน CSS ใช้งานง่ายกว่าสำหรับข้อความ)