HTML Tags: Canvas and SVG

These are the HTML tags you use to make graphics.

TagTypeDescription
<canvas>InlineUsed to draw graphics with canvas scripting API or WebGL API
<svg>InlineUsed to draw graphics using SVG

<canvas>

Used to draw graphics with canvas scripting API or WebGL API.

Possible attributes

  • height=[...]height of the canvas
  • width=[...]width of the canvas
<p>If nothing appears below, <a onclick="location.reload();">refresh</a> the page.</p>

<!-- Canvas -->
<canvas width="150" height="150">
  An alternative text describing what your canvas displays.
</canvas>

<!-- NOTE: Changes to <script> won't be reflected -->
<script>
  const canvas = document.querySelector('canvas');
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'green';
  ctx.fillRect(10, 10, 100, 100);
</script>
| LIVE PREVIEW

If nothing appears below, refresh the page.

An alternative text describing what your canvas displays.

<svg>

Used to draw graphics using SVG.

An <svg> tag defines a new coordinate system and viewport.

NOTE: The xmlns attribute is only required on the outermost svg element of SVG documents. It is unnecessary for inner svg elements or inside HTML documents.

Possible attributes

  • viewbox=[...]the SVG viewport coordinates, i.e. minX minY width height
  • height=[...]the displayed height (viewport height)
  • width=[...]the displayed width (viewport width)
  • x=[...]at which x coordinate a nested <svg> should be put (no effect if given to the outhermost <svg>)
  • y=[...]at which y coordinate a nested <svg> should be put (no effect if given to the outhermost <svg>)
  • preserveAspectRatio=[...]indicates how to fit the viewbox (internal coordinate system) to the viewport (the displayed width and height). The default value is xMidYMid meet. (See possible values here)
<svg viewBox="0 0 300 100" stroke="orange" fill="yellow">
  <circle cx="50" cy="50" r="40" />
  <circle cx="150" cy="50" r="20" />
  <svg viewBox="0 0 10 10" x="200" width="100">
    <circle cx="5" cy="5" r="4" />
  </svg>
</svg>
| LIVE PREVIEW

References