DEV Community

Arhan Khan
Arhan Khan

Posted on

Canvas API for Beginners: Draw Graphics with JavaScript

The Canvas API lets you draw anything in the browser with JavaScript — charts, games, image editors, animations, signatures. If you can imagine it in pixels, you can draw it on a canvas.

A canvas is just an HTML element. You get its 2D drawing context, and then you call methods to draw shapes, lines, text, and images.

<canvas id="board" width="400" height="200"></canvas>
Enter fullscreen mode Exit fullscreen mode
const canvas = document.querySelector('#board');
const ctx = canvas.getContext('2d');

// A blue rectangle
ctx.fillStyle = '#2563eb';
ctx.fillRect(20, 20, 120, 80);

// A red circle
ctx.beginPath();
ctx.arc(250, 60, 40, 0, Math.PI * 2);
ctx.fillStyle = '#ef4444';
ctx.fill();

// Text
ctx.fillStyle = '#111';
ctx.font = '20px sans-serif';
ctx.fillText('Hello, Canvas!', 20, 160);
Enter fullscreen mode Exit fullscreen mode

Every drawing starts with setting a style — a fill colour, a stroke colour, a line width — and then calling a draw method. Rectangles are the simplest. Circles and arcs need beginPath and arc. Text uses fillText, and you can load images with drawImage.

For animation, you redraw the canvas many times a second with requestAnimationFrame, clearing it first with clearRect. Move a shape a few pixels each frame, and it looks like it is moving. That is how most browser games work.

Two tips from experience. First, set the canvas width and height as attributes, not CSS — CSS stretches the drawing and makes it blurry. Second, on high-resolution screens, scale the canvas by devicePixelRatio so your lines stay sharp.

Canvas looks low-level at first, but that is its strength. No framework, no dependencies — just you, some pixels, and total control.

Top comments (0)