Docs/HTML/Canvas

HTML Canvas

Elemen <canvas> digunakan untuk menggambar grafik secara dinamis menggunakan JavaScript.

Kegunaan Canvas

  • Menggambar shapes, teks, dan gambar
  • Membuat animasi dan game
  • Visualisasi data (chart/graph)
  • Manipulasi gambar/foto

Context 2D Methods

  • fillRect() — gambar kotak filled
  • strokeRect() — gambar kotak outline
  • arc() — gambar lingkaran
  • lineTo() — gambar garis
  • fillText() — tulis teks
  • drawImage() — gambar image
index.html
Try It →
<canvas id="myCanvas" width="350" height="200"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Background
ctx.fillStyle = '#F8FAFC';
ctx.fillRect(0, 0, 350, 200);

// Colored rectangles
ctx.fillStyle = '#F06D5B';
ctx.fillRect(20, 20, 80, 60);

ctx.fillStyle = '#6DD5C4';
ctx.fillRect(120, 20, 80, 60);

ctx.fillStyle = '#7EB8F0';
ctx.fillRect(220, 20, 80, 60);

// Circle
ctx.beginPath();
ctx.arc(175, 140, 40, 0, Math.PI * 2);
ctx.fillStyle = '#F5C87A';
ctx.fill();
ctx.strokeStyle = '#E5A84A';
ctx.lineWidth = 3;
ctx.stroke();

// Text
ctx.fillStyle = '#1E293B';
ctx.font = 'bold 14px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('HTML Canvas!', 175, 145);
</script>