Definition
The <canvas> element provides a scriptable 2D bitmap drawing surface where JavaScript paints pixels via the Canvas API—unlike SVG, canvas is raster-based and does not retain a DOM for individual shapes.
Why It Matters
It allows for the direct, pixel-perfect rendering of 2D and 3D graphics within a web browser without the need for external plugins. This capability transformed the web from a static document platform into a powerful engine for games, data visualizations, and interactive art.
Core Concepts
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
</script>
- Raster vs Vector: Canvas manipulates pixels; SVG describes shapes as XML.
getContext('2d'): Accesses the 2D drawing API.- Drawing Methods:
fillRect,strokeRect,beginPath,arc,fillText. - Use Cases: Games, data visualizations, image manipulation, generative art.
- Fallback Content: Text between
<canvas>tags for non-supporting browsers.