HTML Canvas Graphics Tag Explained: How to Draw Shapes, Animations & Interactive Graphics in HTML5
HTML Tutorials · HTML Canvas Graphics Tag · Introduction
What Is the HTML Canvas Tag? Complete Guide to Drawing Graphics in HTML5
🔹 All HTML <canvas> element is used to draw graphics via JavaScript, such as shapes, text, animations, and more. It provides a drawable region in your webpage that you control using JavaScript.
Canvas vs SVG: Which Should You Use?
| Aspect | Canvas | SVG |
|---|---|---|
| Rendering | Pixel-based (bitmap) | Vector-based (DOM elements) |
| Scaling | Can blur when scaled up | Stays crisp at any size |
| Performance with many objects | Better for thousands of moving objects (games, particle effects) | Slower with very large numbers of elements |
| Interactivity | Manual hit-testing required in JavaScript | Each shape is its own DOM element with built-in events |
| Best for | Games, animations, image editing, data visualizations with many points | Icons, logos, charts with a moderate number of shapes, print-quality graphics |
🔹 As a rule of thumb: reach for canvas when you need speed and pixel control over many moving elements, and reach for SVG when you need crisp, resolution-independent shapes that stay interactive as individual DOM elements.
✅ 1. Basic <canvas> Syntax
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;"></canvas>
🔹 On its own, <canvas> is just an empty rectangle — nothing is drawn until JavaScript takes hold of it. The width and height attributes set the canvas's actual drawing resolution, which is different from resizing it with CSS.
✅ 2. Accessing the Canvas with JavaScript
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // 2D rendering context
</script>
🔹 getContext("2d") returns the drawing toolkit — every shape, path, color, and text method used below is called on this ctx object, never directly on the canvas element itself.
✅ 3. Shapes
// Rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 100, 50); // x, y, width, height
// Clear part of the canvas
ctx.clearRect(30, 30, 50, 25);
// Outline only
ctx.strokeStyle = "red";
ctx.strokeRect(10, 10, 150, 75);
🔹 fillRect draws a solid rectangle, strokeRect draws just the outline, and clearRect erases pixels back to transparent — useful for punching a hole in a shape or clearing a region before redrawing the next animation frame.
✅ 4. Paths (Lines & Curves)
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 100);
ctx.closePath();
ctx.stroke();
🔹 beginPath() starts a fresh shape, moveTo lifts the "pen" to a starting point without drawing, lineTo draws a straight line to the next point, and closePath() connects back to the start — together they form a triangle outline here.
✅ 5. Circle / Arc
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle
ctx.fillStyle = "green";
ctx.fill();
🔹 arc() takes angles in radians, not degrees, which is why a full circle uses Math.PI * 2. Changing the endAngle to something smaller, like Math.PI, draws only half the circle instead.
✅ 6. 🖋️ Text
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas!", 50, 100); // text, x, y
🔹 fillText draws solid text, while the companion method strokeText draws just the text outline. Set font before calling either, exactly like setting a CSS font shorthand.
✅ 7. Draw a Line
<canvas id="lineCanvas" width="200" height="100" style="border:1px solid #000;"></canvas>
<script>
const c = document.getElementById("lineCanvas");
const ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
🔹 Notice this example skips beginPath() — for a single simple line that's harmless, but once you draw more than one path on the same canvas, always call beginPath() first, or the new line will connect to the end of the previous one.
✅ 8. 🖼️ Images
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = "image.jpg";
🔹 Images must finish loading before they can be drawn, which is why drawImage is called inside the onload callback rather than immediately after setting src. drawImage also accepts optional width/height arguments to scale the image, and can crop a sub-region of a source image for sprite-sheet style graphics.
Animating a Canvas
🔹 A static shape is just the first step — canvas becomes powerful once you animate it. The standard pattern is to clear the canvas, redraw everything at a new position, and repeat using requestAnimationFrame, which asks the browser to call your function right before the next screen repaint for smooth, efficient motion.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "purple";
ctx.fillRect(x, 40, 30, 30);
x = (x + 2) % canvas.width;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
🔹 requestAnimationFrame is preferred over setInterval for animation because it automatically syncs with the display's refresh rate and pauses itself when the tab isn't visible, saving battery and CPU.
Common Canvas Methods at a Glance
| Method | Purpose |
|---|---|
| fillRect(x, y, w, h) | Draws a filled rectangle |
| strokeRect(x, y, w, h) | Draws a rectangle outline |
| clearRect(x, y, w, h) | Clears a rectangular region to transparent |
| beginPath() / closePath() | Starts/closes a custom path shape |
| moveTo(x, y) / lineTo(x, y) | Moves the pen or draws a straight line |
| arc(x, y, r, start, end) | Draws a circle or arc segment |
| fillText(text, x, y) | Draws filled text |
| drawImage(img, x, y) | Draws an image onto the canvas |
Common Mistakes with HTML Canvas
- 🔹 Setting canvas size with CSS instead of the width/height attributes: this stretches and blurs the drawing rather than giving it more actual pixels to draw on.
- 🔹 Forgetting beginPath() between shapes: new paths silently connect to the end of the previous one, creating unwanted stray lines.
- 🔹 Drawing an image before it has loaded: calling drawImage outside the onload callback often draws nothing at all.
- 🔹 Using setInterval for animation: it doesn't sync with the screen's refresh rate and keeps running even on a hidden tab, wasting battery.
- 🔹 Forgetting accessibility: canvas content is invisible to screen readers by default, so important information needs a text alternative.
HTML Canvas Best Practices
- 🔹 Set the drawing resolution with the width/height attributes, and use CSS only for layout positioning, not resizing.
- 🔹 Always pair beginPath() with each new shape when drawing multiple paths.
- 🔹 Use requestAnimationFrame instead of setInterval for any animation loop.
- 🔹 Wait for img.onload before calling drawImage.
- 🔹 Provide fallback text or an aria-label describing important canvas content for accessibility.
- 🔹 For a huge number of static shapes with light interactivity needs, benchmark against SVG before committing to canvas — it isn't always the faster choice for simple cases.
Try It Yourself (Copy This Code and Paste. See how it works). Paste any of the eight examples above into the live playground below.
Live Code Preview
Frequently Asked Questions About HTML Canvas
What is HTML Canvas?
HTML Canvas is an element used to draw graphics, shapes, animations, and interactive visuals using JavaScript.
What is the use of canvas in HTML?
Canvas is used to create dynamic graphics such as charts, games, animations, and drawings on web pages.
Is HTML Canvas better than SVG?
Canvas is better for complex animations and pixel-based graphics, while SVG is better for scalable vector graphics.
Do I need JavaScript for Canvas?
Yes, JavaScript is required to draw and control graphics inside the canvas element.
Can canvas graphics be animated?
Yes, by clearing and redrawing the canvas repeatedly using requestAnimationFrame, you can create smooth animations.
Is canvas content accessible to screen readers?
Not by default, since canvas draws pixels rather than DOM elements, so accessible fallback content or ARIA labels should be added for important information.
Conclusion
🔹 The HTML <canvas> element hands you a blank, pixel-based drawing surface and a rich JavaScript API to fill it with shapes, paths, text, and images. Once the basics of rectangles, paths, arcs, and text click, animating them with requestAnimationFrame opens the door to games, data visualizations, drawing tools, and interactive graphics of almost any kind. Work through the eight examples above, then try combining a shape, some text, and a simple animation loop in the live playground to see canvas come together.