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

วิธีวาดบน Canvas ด้วย JavaScript

การวาดบน HTML <canvas> ต้องใช้ JavaScript ขั้นตอน:

  1. หา canvas element ด้วย getElementById()
  2. ดึง drawing context ด้วย getContext('2d') (มี methods/properties สำหรับวาด)
  3. วาดรูปทรงต่างๆ

ตัวอย่าง: วาดสี่เหลี่ยมสีฟ้า

<!DOCTYPE html> <html>
  <head>
    <title>HTML Canvas</title>
  </head>
  <body>
    <canvas id="newCanvas" width="400" height="250" style="border:2px solid #000000;"></canvas>
    <script>
      var canvas = document.getElementById("newCanvas");
      var ctxt = canvas.getContext("2d");
      ctxt.fillStyle = "#56A7E2";
      ctxt.fillRect(0, 0, 250, 120);
    </script>
  </body>
</html>

Canvas 2D Context Methods ยอดนิยม

Methodคำอธิบาย
fillRect(x, y, w, h)วาดสี่เหลี่ยมเติมสี
strokeRect(x, y, w, h)วาดกรอบสี่เหลี่ยม
clearRect(x, y, w, h)ล้างพื้นที่
fillText(text, x, y)เขียนข้อความเติมสี
drawImage(img, x, y)วาดรูปภาพ
beginPath(), moveTo(), lineTo(), arc()วาดเส้นทางซับซ้อน

สไตล์สำคัญ

  • fillStyle – สีเติม (color, gradient, pattern)
  • strokeStyle – สีขอบ
  • lineWidth – ความหนาเส้น
  • font – ฟอนต์ข้อความ

หมายเหตุ: Canvas เป็น bitmap (pixel-based) ไม่ใช่ vector ขยายใหญ่จะแตก