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

วิธีสร้างกราฟิกด้วยสคริปต์ใน HTML

เพื่อสร้างกราฟิกด้วยสคริปต์ ใช้แท็ก <canvas> แท็ก HTML <canvas> ใช้สำหรับวาดกราฟิก แอนิเมชัน ฯลฯ โดยใช้สคริปต์ (JavaScript)

แอตทริบิวต์ของ <canvas>

แอตทริบิวต์ ค่า คำอธิบาย
height pixels ระบุความสูงของ canvas
width pixels ระบุความกว้างของ canvas

ตัวอย่าง

คุณสามารถลองรันโค้ดต่อไปนี้เพื่อใช้งานแท็ก <canvas> และสร้างกราฟิก:

<!DOCTYPE html> 
<html> 
  <head> 
    <title>HTML Canvas Tag</title> 
  </head> 
  <body> 
    <canvas id="newCanvas">เบราว์เซอร์ของคุณไม่รองรับ canvas tag</canvas> 
    <script> 
      var c = document.getElementById('newCanvas'); 
      var ctx = c.getContext('2d'); 
      ctx.fillStyle = '#00AEEF'; 
      ctx.fillRect(0,0,180,50); 
    </script> 
  </body> 
</html>

ความสามารถของ Canvas 2D Context:

  • รูปทรง: fillRect, strokeRect, arc, bezierCurveTo
  • เส้นทาง: beginPath, moveTo, lineTo, closePath
  • สไตล์: fillStyle, strokeStyle, lineWidth, shadow, gradient
  • ข้อความ: fillText, strokeText, font, textAlign
  • รูปภาพ: drawImage
  • Transform: translate, rotate, scale, transform

WebGL: ใช้ canvas.getContext('webgl') หรือ 'webgl2' สำหรับ 3D graphics