What does the <canvas> element do?
The <canvas> element creates a drawing area on the web page, where JavaScript can be used to dynamically draw graphics, animation, charts, games, visualizations, and even 3D objects.
On its own, <canvas> is an empty container, like a canvas in Photoshop:
without code: just a rectangle;
with JavaScript: a living, interactive surface.
1. Simplest example
<canvas id="myCanvas" width="300" height="200"></canvas>What happens:
- a 300x200 pixel area is created;
- by default: transparent and empty;
- without a script, nothing gets drawn.
2. How to work with it
Drawing is done through a JavaScript API: first you get the "context" (the drawing object), then you call methods on it.
Example: drawing a circle:
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 2D drawing context
ctx.fillStyle = 'skyblue';
ctx.beginPath();
ctx.arc(150, 100, 70, 0, Math.PI * 2); // center x,y, radius, angles
ctx.fill();
</script>Result: a light blue circle appears on the page.
3. Main context modes
| Context type | Purpose |
|---|---|
"2d" | Working with regular 2D graphics (shapes, lines, text, images) |
"webgl" | 3D graphics with hardware acceleration (via the WebGL API) |
Example:
const ctx = canvas.getContext('webgl');4. What you can draw on <canvas>
- shapes (lines, rectangles, circles);
- text and fonts;
- raster images;
- animations (via
requestAnimationFrame); - data visualizations, games, 3D scenes.
5. Important attributes
| Attribute | Purpose | Example |
|---|---|---|
width | canvas width in pixels | width="500" |
height | canvas height | height="300" |
| (if not set) | defaults to 300×150 | - |
Dimensions should be set with attributes, not CSS, otherwise the picture can distort when scaled.
6. Example: drawing text
ctx.font = "24px Arial";
ctx.fillStyle = "darkred";
ctx.fillText("Hello, Canvas!", 50, 100);7. Example: animation
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();The square will smoothly move to the right.
Summary:
| Property | Value |
|---|---|
| Tag | <canvas> |
| Purpose | A canvas for dynamic drawing via JavaScript |
| Context | 2d or webgl |
| Feature | Empty on its own: everything is drawn by a script |
| Use cases | Games, charts, animations, data visualization, effects |
In simple terms:
<canvas> is a digital canvas
where you can draw anything you like,
from simple shapes to complex interactive scenes,
as long as you have a brush, meaning JavaScript.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.