HTML Canvas
The <canvas> element is a blank bitmap surface you draw on with JavaScript. It's used for charts, games, image editing, and procedural graphics.
Two-step setup
- Add a
<canvas>to the HTML with a width and height. - Grab its 2D drawing context in JavaScript and call drawing methods.
<canvas id="cv" width="300" height="120"></canvas>
<script>
const ctx = document.getElementById('cv').getContext('2d');
ctx.fillStyle = '#04AA6D';
ctx.fillRect(20, 20, 100, 60);
ctx.fillStyle = '#fff';
ctx.font = '18px Verdana';
ctx.fillText('Hello!', 35, 58);
</script>
Useful 2D context methods
| Method | Draws |
|---|---|
fillRect(x, y, w, h) | Filled rectangle. |
strokeRect(x, y, w, h) | Outlined rectangle. |
beginPath() / moveTo() / lineTo() / stroke() | Custom path. |
arc(x, y, r, start, end) | Circles and arcs. |
fillText(text, x, y) | Text. |
drawImage(img, x, y) | An image or another canvas. |
Canvas vs SVG: Canvas is a bitmap — fast at thousands of moving particles, but you can't restyle individual shapes after drawing them. SVG is a vector DOM tree — easier to style and animate per shape, but slower at massive numbers of objects.
Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Canvas</title>
</head>
<body>
<h1>HTML Canvas</h1>
<p>This is a demo page for the "HTML Canvas" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Create a 600×400 drawing surface that JavaScript can target.
<
id="paint" width="600" height="400"></
>
Same word as the painter's surface.
Discussion
Loading…