Langsung ke konten

Canvas dan SVG di HTML: Pengenalan Grafik dan Animasi

Pelajari pengenalan canvas dan SVG di HTML. Pahami kapan menggunakan Canvas vs SVG untuk membuat grafik, animasi, dan visualisasi data.

Belajar HTML untuk Pemula
Belajar HTML untuk Pemula
Advertisement

Artikel ini merupakan bagian dari seri Belajar HTML untuk Pemula di hanifmu.com. Setelah memahami SEO basics, kita masuk ke modul HTML5 Features. Topik pertama: Canvas dan SVG untuk membuat grafik.

Apa itu Canvas?

Canvas adalah elemen HTML5 untuk menggambar grafik menggunakan JavaScript. Canvas menyediakan area kosong yang bisa kamu gambar dengan kode.

<canvas id="myCanvas" width="400" height="200"></canvas>

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

  // Gambar persegi
  ctx.fillStyle = '#4caf50';
  ctx.fillRect(50, 50, 100, 50);

  // Gambar lingkaran
  ctx.fillStyle = '#2196f3';
  ctx.beginPath();
  ctx.arc(250, 75, 40, 0, Math.PI * 2);
  ctx.fill();
</script>

Metode Canvas Dasar

Menggambar Bentuk

const ctx = canvas.getContext('2d');

// Persegi
ctx.fillRect(x, y, width, height);

// Garis
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();

// Lingkaran
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.fill();

// Teks
ctx.font = '20px Arial';
ctx.fillText('Hello', x, y);

Mengatur Warna

// Warna isi
ctx.fillStyle = '#ff0000';

// Warna garis
ctx.strokeStyle = '#000000';

// Ketebalan garis
ctx.lineWidth = 2;

Apa itu SVG?

SVG (Scalable Vector Graphics) adalah format grafik vektor yang digunakan langsung di HTML. Berbeda dengan Canvas, SVG menggunakan XML untuk mendefinisikan grafik.

<svg width="400" height="200">
  <!-- Persegi -->
  <rect x="50" y="50" width="100" height="50" fill="#4caf50" />

  <!-- Lingkaran -->
  <circle cx="250" cy="75" r="40" fill="#2196f3" />

  <!-- Teks -->
  <text x="150" y="150" font-size="20">Hello SVG</text>
</svg>

Elemen SVG Dasar

<rect> — Persegi

<rect
  x="10"
  y="10"
  width="100"
  height="50"
  fill="blue"
  stroke="black"
  stroke-width="2"
/>

<circle> — Lingkaran

<circle
  cx="100"
  cy="100"
  r="50"
  fill="red"
/>

<ellipse> — Elips

<ellipse
  cx="100"
  cy="100"
  rx="80"
  ry="40"
  fill="green"
/>

<line> — Garis

<line
  x1="0"
  y1="0"
  x2="100"
  y2="100"
  stroke="black"
  stroke-width="2"
/>

<polyline> — Polylines

<polyline
  points="0,0 50,50 100,0 150,50"
  fill="none"
  stroke="blue"
  stroke-width="2"
/>

<polygon> — Polygon

<polygon
  points="100,10 40,198 190,78 10,78 160,198"
  fill="yellow"
  stroke="orange"
  stroke-width="2"
/>

<path> — Path

<path
  d="M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80"
  fill="transparent"
  stroke="red"
  stroke-width="2"
/>

Canvas vs SVG

AspekCanvasSVG
RenderingPixel-based (raster)Vektor
ResolusiBergantung ukuran canvasSkala tanpa pecah
InteraksiSulit (perlu JavaScript)Mudah (setiap elemen bisa di-event)
PerformaBaik untuk banyak objekLambat untuk banyak elemen
AnimasiPerlu redraw manualBisa animasi CSS
AksesibilitasKurangLebih baik
PenggunaanGame, visualisasi data kompleksIkon, logo, grafik sederhana

Kapan Menggunakan Canvas?

  • Game — Grafik game 2D
  • Visualisasi data — Chart, grafik interaktif
  • Efek visual — Animasi kompleks
  • Pengolahan gambar — Filter, manipulasi foto
  • Banyak objek — Ratusan ribu objek
<!-- Contoh: Chart sederhana dengan Canvas -->
<canvas id="chart" width="400" height="300"></canvas>

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

  // Data penjualan
  const data = [80, 120, 100, 150, 90];
  const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei'];
  const colors = ['#4caf50', '#2196f3', '#ff9800', '#e91e63', '#9c27b0'];

  // Gambar bar chart
  data.forEach((value, index) => {
    ctx.fillStyle = colors[index];
    ctx.fillRect(index * 80 + 20, 300 - value, 60, value);

    // Label
    ctx.fillStyle = '#000';
    ctx.fillText(labels[index], index * 80 + 35, 290);
  });
</script>

Kapan Menggunakan SVG?

  • Ikon — Ikon yang bisa di-scale
  • Logo — Logo perusahaan
  • Grafik sederhana — Diagram alur
  • Animasi CSS — Animasi yang bisa dikontrol CSS
  • Interaksi — Klik, hover pada elemen
<!-- Contoh: Ikon SVG -->
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
  <polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>

SVG dengan CSS

SVG bisa di-style dengan CSS:

<svg width="200" height="200">
  <circle class="my-circle" cx="100" cy="100" r="50" />
</svg>

<style>
  .my-circle {
    fill: blue;
    transition: fill 0.3s ease;
  }

  .my-circle:hover {
    fill: red;
    cursor: pointer;
  }
</style>

SVG dengan JavaScript

SVG bisa dikontrol dengan JavaScript:

<svg id="mySvg" width="200" height="200">
  <circle id="myCircle" cx="100" cy="100" r="50" fill="blue" />
</svg>

<script>
  const circle = document.getElementById('myCircle');

  circle.addEventListener('click', () => {
    circle.setAttribute('fill', 'red');
    circle.setAttribute('r', '70');
  });
</script>

Best Practice Canvas dan SVG

  1. Gunakan Canvas untuk grafik kompleks — Game, visualisasi data
  2. Gunakan SVG untuk ikon dan logo — Skala tanpa pecah
  3. Optimasi Canvas — Gunakan requestAnimationFrame untuk animasi
  4. Optimasi SVG — Hapus atribut yang tidak perlu
  5. Aksesibilitas SVG — Tambahkan role="img" dan aria-label

Ringkasan

  • Canvas untuk grafik pixel-based (raster)
  • SVG untuk grafik vektor (skala tanpa pecah)
  • Canvas lebih cepat untuk banyak objek
  • SVG lebih mudah untuk interaksi dan animasi CSS
  • Canvas untuk game dan visualisasi data
  • SVG untuk ikon, logo, grafik sederhana

Langkah Selanjutnya

Kamu sudah memahami Canvas dan SVG. Artikel selanjutnya membahas Web Storage, localStorage dan sessionStorage untuk menyimpan data di browser.