Advanced HTML · 3 min read
Media, Canvas and SVG
Responsive images, video with captions, drawing and animating with canvas, and inline SVG.
The web has three ways to show graphics, each with a job:
| Tool | Model | Best for |
|---|---|---|
<img> / <picture> | A file the browser decodes | Photos, screenshots |
<svg> | Vector shapes in the DOM | Icons, logos, diagrams (like the animated diagrams in these lessons) |
<canvas> | A pixel buffer you paint with JavaScript | Games, charts with thousands of points, effects |
Responsive images
html
<picture>
<source type="image/avif" srcset="hero.avif">
<source type="image/webp" srcset="hero.webp">
<img src="hero.jpg" alt="Retro computer lab"
srcset="hero-640.jpg 640w, hero-1280.jpg 1280w"
sizes="(min-width: 800px) 50vw, 100vw"
width="1280" height="720" loading="lazy" decoding="async">
</picture>srcset+sizeslet the browser pick the smallest file that looks sharp.widthandheightreserve space, so the layout does not jump (good for Core Web Vitals).loading="lazy"defers off-screen images.
Video with captions
html
<video controls preload="metadata" poster="poster.jpg" width="640">
<source src="demo.webm" type="video/webm">
<track kind="captions" src="demo.en.vtt" srclang="en" label="English" default>
</video>Captions (<track>) make video usable for deaf viewers and for people watching with sound off.
Canvas: an animation loop
Canvas is immediate mode: you clear and redraw every frame. requestAnimationFrame syncs with the display and pauses in background tabs.
<canvas id="c" width="320" height="180" aria-label="Bouncing blocks animation"></canvas>Edit this example in the Playground.
Inline SVG
SVG lives in the DOM, so CSS and JavaScript can style it, and it stays sharp at any size.
<svg viewBox="0 0 24 24" width="96" height="96" role="img" aria-labelledby="t">
<title id="t">NEAR diploma badge</title>
<circle cx="12" cy="12" r="10" class="ring"/>
<path d="M7 12l3 3 7-7" class="check"/>
</svg>Edit this example in the Playground.
viewBox defines the coordinate system; width/height define the rendered size. The stroke-dasharray trick "draws" the checkmark.
Summary
Use <picture> and srcset for photos, <track> for captions, SVG for crisp UI graphics, and canvas plus requestAnimationFrame when you need to paint pixels fast.
Saved in this browser.