What is the Canvas API?
The Canvas API is a part of the HTML5 specification that allows developers to draw graphics, animations, charts, images, and even games directly in the browser using JavaScript.
It provides a powerful, low-level way to render visual content on a web page inside an HTML <canvas> element.
š§© Basic Structure
html
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Draw a red rectangle
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
</script>
š§ Canvas Contexts
| Context | Use Case |
|---|---|
2d | 2D graphics (shapes, images, text) |
webgl | 3D rendering using WebGL API |
Ā
Most use cases (charts, games, animations) use the 2D context.
šļø Common Canvas Drawing Functions
| Function | Description |
|---|---|
fillRect(x, y, w, h) | Draw a filled rectangle |
strokeRect() | Draw rectangle outline |
clearRect() | Clear an area of the canvas |
beginPath() | Start a new path (for shapes) |
moveTo() / lineTo() | Draw lines |
arc() / arcTo() | Draw circles/curves |
fillText() / strokeText() | Draw text |
drawImage() | Draw images (from URL, file, etc.) |
Ā
š Canvas Use Cases
| Use Case | Example |
|---|---|
| Charts/Graphs | Chart.js (built on Canvas) |
| Game development | 2D browser-based games |
| Data visualization | Real-time dashboard rendering |
| Animations | Interactive UIs and effects |
| Image manipulation | Filters, cropping, rendering |
| Signature pads | Drawing input from user |
Ā
š Basic Animation with Canvas
js
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "blue";
ctx.fillRect(x, 50, 50, 50);
x += 1;
requestAnimationFrame(animate);
}
animate();
This moves a blue square across the screen.
š§° Popular Libraries Built on Canvas
| Library | Purpose |
|---|---|
| Chart.js | Beautiful responsive charts |
| Fabric.js | Canvas object management |
| PixiJS | High-performance 2D rendering |
| Konva.js | Drawing & animations with layering |
| Paper.js | Vector graphics scripting |
Ā
ā ļø Canvas vs SVG
| Feature | Canvas | SVG |
|---|---|---|
| Performance | Better for large, complex scenes | Slower with many elements |
| Interactivity | Manual handling (e.g., mouse pos) | Built-in DOM support |
| Accessibility | Harder (pixel-based) | Better (DOM-based) |
| Use Case | Games, animation, pixel drawing | Icons, infographics |
Ā
ā Tips for Using Canvas Effectively
Always check if the context exists (
if (ctx) { ... })Use
requestAnimationFrame()for smooth animationsHandle canvas resizing to fit dynamic layouts
Clean up with
clearRect()before redrawing frames































































































































































