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

วิธีสร้าง Linear Gradient (คุณลักษณะเส้นตรง) ใน HTML5 Canvas

ใช้ createLinearGradient() สร้าง gradient แบบเส้นตรง จากจุดเริ่มต้นไปจุดสิ้นสุด

Syntax

const gradient = ctx.createLinearGradient(x0, y0, x1, y1);

Parameter

Parameterคำอธิบาย
x0, y0จุดเริ่มต้น (start point)
x1, y1จุดสิ้นสุด (end point)

ทิศทาง Gradient

ทิศทางParameters
ซ้าย → ขวาcreateLinearGradient(0, 0, width, 0)
บน → ล่างcreateLinearGradient(0, 0, 0, height)
มุม (45°)createLinearGradient(0, 0, width, height)
กำหนดเองจุดใดก็ได้

ตัวอย่างเต็ม

<!DOCTYPE html>
<html>
<body>
  <canvas id="canvas" width="450" height="250" style="border:1px solid #ddd"></canvas>
  <script>
    const c = document.getElementById('canvas');
    const ctx = c.getContext('2d');
    
    // Horizontal gradient: (0,0) → (170,0)
    const grad = ctx.createLinearGradient(0, 0, 170, 0);
    grad.addColorStop(0.5, '#E44D26'); // 50% - orange-red
    grad.addColorStop(1, '#66CC00');   // 100% - green
    
    ctx.fillStyle = grad;
    ctx.fillRect(50, 80, 300, 100);
  </script>
</body>
</html>

การเพิ่มสี (Color Stops)

grad.addColorStop(0, 'red');      // 0% - เริ่มต้น
grad.addColorStop(0.3, 'yellow'); // 30%
grad.addColorStop(0.7, 'blue');   // 70%
grad.addColorStop(1, 'green');    // 100% - สิ้นสุด

การใช้งาน

  • ctx.fillStyle = grad - ใช้กับ fill (fillRect, fillText, arc fill)
  • ctx.strokeStyle = grad - ใช้กับ stroke (strokeRect, strokeText, line)
  • ทำงานกับ shape ใดๆ ที่มี fill/stroke

CSS Gradient Alternative

.css-gradient {
  background: linear-gradient(90deg, #E44D26 50%, #66CC00 100%);
  /* รองรับทุก browser ใหม่ ไม่ต้องใช้ canvas */
}

สำหรับ UI backgrounds ควรใช้ CSS Gradient (performance ดีกว่า, responsive อัตโนมัติ)