๐งฉ What is the Canvas?
The HTML <canvas> element is like a digital whiteboard โ a blank area where you can draw anything using JavaScript.
Shapes, images, animations, and even video effects โ all can be rendered dynamically, pixel by pixel.
<canvas id="myCanvas" width="400" height="300"></canvas>
By default, the canvas has a size of 300 ร 150 pixels, but you can easily adjust it using the width and height attributes.
To start drawing, you need to get its rendering context โ the interface that gives you access to all the drawing tools:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 2D drawing surface
๐๏ธ Drawing Shapes โ The Core Canvas APIs
The CanvasRenderingContext2D API provides a rich set of methods to draw shapes, text, and paths.
| Shape / Action | Common API | Example |
|---|---|---|
| Filled Rectangle | fillRect(x, y, width, height) |
ctx.fillRect(50, 50, 100, 60) |
| Outlined Rectangle | strokeRect(x, y, width, height) |
ctx.strokeRect(50, 50, 100, 60) |
| Circle / Arc | arc(x, y, radius, startAngle, endAngle) |
ctx.arc(100, 75, 50, 0, Math.PI * 2) |
| Custom Path / Line |
beginPath(), moveTo(), lineTo(), stroke()
|
Draw polygons or freeform shapes |
| Text |
fillText(text, x, y) / strokeText(text, x, y)
|
ctx.fillText("Hello Canvas", 50, 50) |
You can also style your shapes easily:
ctx.fillStyle = 'skyblue';
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
๐ผ๏ธ Image Manipulation โ Pixel-Level Power
Canvas gives you direct access to pixels, allowing for advanced image manipulation.
๐ก Popular Use Cases:
- Cropping: Draw only a portion of an image
- Capturing: Grab a frame from a live video feed
- Zooming & Panning: Scale or move specific regions
-
Color Picking: Sample pixel colors using
getImageData()
Example: Cropping and drawing an image
const img = new Image();
img.src = 'photo.jpg';
img.onload = () => {
// Draw a cropped section of the image
ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
๐พ Exporting and Saving Drawings
Once your masterpiece is ready, you can export the canvas as an image:
const dataURL = canvas.toDataURL('image/png');
This returns a Base64-encoded PNG that you can:
- Display as an
<img> - Download directly
- Send to your backend for saving
๐ Transformations โ Move, Rotate, Scale, and More
Canvas supports 2D transformations that let you move, rotate, or scale everything you draw.
| Transformation | API | Description |
|---|---|---|
| Translate | ctx.translate(x, y) |
Move the origin to a new position |
| Rotate | ctx.rotate(angleInRadians) |
Rotate everything drawn after this |
| Scale | ctx.scale(xFactor, yFactor) |
Enlarge, shrink, or mirror shapes |
| Transform | ctx.transform(a, b, c, d, e, f) |
Apply a full transformation matrix |
Example:
ctx.translate(100, 100);
ctx.rotate(Math.PI / 4);
ctx.fillRect(0, 0, 100, 50);
Each transformation modifies the drawing coordinate system โ ideal for rotating shapes, rotating charts, or applying visual effects.
๐ฌ Animations โ Bringing the Canvas to Life
Canvas excels at real-time, smooth animations.
You can create bouncing balls, moving graphs, or complex particle effects using requestAnimationFrame():
let x = 10, dx = 2;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, 75, 20, 0, Math.PI * 2);
ctx.fillStyle = 'orange';
ctx.fill();
x += dx;
if (x > canvas.width - 20 || x < 20) dx *= -1;
requestAnimationFrame(animate);
}
animate();
Each frame clears the canvas and redraws the updated state, creating a smooth motion effect.
๐ Real-World Examples โ Canvas in Action
The Canvas API isnโt just for demos โ itโs powering some of the most interactive and high-performance web experiences out there.
| Website / Product | Use Case | Description |
|---|---|---|
| Google Maps | Map Rendering | Roads, labels, and markers are drawn dynamically on canvas for smooth panning and zooming. |
| Figma | Collaborative Design Editor | The design canvas, shapes, and drawing tools are built using a custom canvas rendering engine. |
| Canva | Online Graphic Design | Uses canvas for real-time drawing, text rendering, and applying visual filters to images. |
| Photopea | Browser-based Photoshop Alternative | Heavily uses canvas for layer rendering, filters, and pixel-level editing. |
| Chart.js | Data Visualization | All charts (line, bar, radar, etc.) are rendered efficiently on canvas for performance. |
| Google Docs / Slides (Drawing Mode) | Freehand Drawing | Uses canvas to capture drawings, highlights, and annotations. |
| CodePen Playground Previews | Live Render Output | Renders real-time visual demos and 2D/3D animations directly inside canvas. |
These examples show just how versatile and production-ready the Canvas API really is โ from creative tools to productivity suites.
๐ Quick Recap
The <canvas> element turns your web page into a programmable drawing surface, giving you full pixel-level control.
You can use it to build:
- ๐ฎ Interactive 2D games
- ๐ Real-time charts and dashboards
- ๐ผ๏ธ Image editors and whiteboards
- ๐ซ Animations and particle effects
- ๐ฅ Video filters and visual effects
Whether youโre crafting simple shapes or architecting a design editor, Canvas gives you the freedom and flexibility to bring your graphics to life directly in the browser.
Top comments (0)