คุณสมบัติ fillStyle ของ Canvas คืออะไร?
คุณสมบัติ fillStyle ของ HTML Canvas ใช้สำหรับ ตั้งค่ารูปแบบการทา (Fill Style)** สำหรับรูปทรงที่จะวาดต่อไป ค่าเริ่มต้นคือ #000000 (สีดำ) รองรับ 3 รูปแบบ: สีเดี่ยว กรีเดียน และแพทเทิร์น
ไวยากรณ์ (Syntax)
ctx.fillStyle = color | gradient | pattern;
ประเภทค่าที่รองรับ
| ประเภท | ตัวอย่าง | คำอธิบาย |
|---|---|---|
| Color (CSS Color) | "red", "#ff0000", "rgb(255,0,0)", "rgba(255,0,0,0.5)" | สีเดี่ยว รองรับทุกรูปแบบ CSS |
| Gradient | ctx.createLinearGradient(), ctx.createRadialGradient() | ไล่สีเส้นตรง หรือไล่สีวงกลม |
| Pattern | ctx.createPattern(image, "repeat") | ใช้รูปภาพเป็นแพทเทิร์นซ้ำ |
ตัวอย่าง: Linear Gradient
<!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");
// สร้าง Linear Gradient จากซ้ายไปขวา
var gradient = ctx.createLinearGradient(0, 0, 130, 0);
gradient.addColorStop(0, "blue"); // 0% = สีน้ำเงิน
gradient.addColorStop(0.8, "green"); // 80% = สีเขียว
gradient.addColorStop(1, "yellow"); // 100% = สีเหลือง
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 500, 350); // ทาสีเต็ม Canvas
</script>
</body>
</html>
ตัวอย่าง: Pattern (รูปภาพซ้ำ)
var img = new Image();
img.src = "pattern.png";
img.onload = function() {
var pattern = ctx.createPattern(img, "repeat"); // repeat, repeat-x, repeat-y, no-repeat
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 200);
};
จุดสำคัญ
fillStyleส่งผลต่อfill(),fillRect(),fillText()ที่เรียกหลังจากตั้งค่า- Gradient ต้องสร้างด้วย
createLinearGradient(x0,y0,x1,y1)หรือcreateRadialGradient(x0,y0,r0,x1,y1,r1) addColorStop(offset, color)offset = 0.0 ถึง 1.0- Pattern ใช้รูปภาพ
<img>,<canvas>, หรือ<video>