← Back to Tutorials Chapter 7

Graphics

SVG (Scalable Vector Graphics)

SVG is an XML-based format for vector graphics. Unlike raster images (JPEG, PNG), SVGs scale infinitely without losing quality.

Basic Shapes

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <!-- Rectangle -->
  <rect x="10" y="10" width="80" height="50" fill="blue" stroke="black" stroke-width="2"/>

  <!-- Circle -->
  <circle cx="150" cy="50" r="30" fill="red"/>

  <!-- Ellipse -->
  <ellipse cx="50" cy="130" rx="40" ry="20" fill="green"/>

  <!-- Line -->
  <line x1="120" y1="100" x2="180" y2="160" stroke="orange" stroke-width="3"/>

  <!-- Polygon (triangle) -->
  <polygon points="100,170 70,200 130,200" fill="purple"/>
</svg>

Rendered result:

Text in SVG

<svg width="300" height="100" xmlns="http://www.w3.org/2000/svg">
  <text x="10" y="40" font-family="Arial" font-size="24" fill="navy" font-weight="bold">
    Hello, SVG!
  </text>
  <text x="10" y="70" font-family="Arial" font-size="14" fill="gray">
    Scalable Vector Graphics
  </text>
</svg>

Canvas

The <canvas> element provides a pixel-based drawing surface controlled by JavaScript:

<canvas id="myCanvas" width="400" height="250" style="border:1px solid #ccc;"></canvas>

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

  // Rectangle
  ctx.fillStyle = 'blue';
  ctx.fillRect(20, 20, 100, 80);

  // Circle
  ctx.beginPath();
  ctx.arc(200, 100, 40, 0, Math.PI * 2);
  ctx.fillStyle = 'red';
  ctx.fill();

  // Line
  ctx.beginPath();
  ctx.moveTo(20, 150);
  ctx.lineTo(380, 150);
  ctx.strokeStyle = 'green';
  ctx.lineWidth = 3;
  ctx.stroke();

  // Text
  ctx.font = '20px Arial';
  ctx.fillStyle = 'black';
  ctx.fillText('Hello, Canvas!', 120, 220);
</script>

SVG vs Canvas

SVGCanvas
Vector-based (resolution independent)Pixel-based (resolution dependent)
Each element is a DOM nodeSingle bitmap surface
Better for static, interactive graphicsBetter for animations, games, real-time
Accessible (elements can have ARIA)Not accessible by default

Practice Task

Create an HTML page that draws: