Sobes.tech
Middle

What is the difference between Canvas and SVG?

sobes.tech AI

Answer from AI

Canvas is a raster API for drawing graphics on the fly using JavaScript. It draws pixels on the canvas.

SVG (Scalable Vector Graphics) is an XML format for describing two-dimensional vector graphics. It describes shapes, lines, text, etc.

Main differences:

  • Basis: Canvas — pixels, SVG — vectors (mathematical descriptions).
  • Drawing method: Canvas — imperative (drawing commands), SVG — declarative (element descriptions).
  • Scaling: Canvas scales with loss of quality (raster), SVG scales without loss of quality (vector).
  • Performance: Canvas is better suited for dynamic graphics, animations, games. SVG is better for static, complex graphics, diagrams.
  • Accessibility: SVG elements are accessible via DOM, can be modified with CSS and JavaScript. Canvas draws at the pixel level, individual elements are not accessible.
  • Interactivity: Interactivity in SVG is built into the elements. In Canvas, you need to track mouse/touch events and determine which pixels they correspond to.
  • Format: Canvas is an element <canvas> and JavaScript API. SVG is a standalone XML format that can be embedded directly into HTML or used as a file (.svg).

Example of creating a circle:

// Canvas
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
<!-- SVG -->
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" fill="red" />
</svg>