JS Canvas
The <canvas> element is a fixed-size pixel surface you draw on with JavaScript. The 2D context covers shapes, text, images, transforms, gradients, and compositing.
Setup
HTML + JS
<canvas id="c" width="400" height="300"></canvas>
const ctx = document.getElementById("c").getContext("2d");
Common drawing calls
JS
// Solid rectangle
ctx.fillStyle = "#04AA6D";
ctx.fillRect(20, 20, 100, 60);
// Outline
ctx.strokeStyle = "#222";
ctx.lineWidth = 2;
ctx.strokeRect(20, 20, 100, 60);
// Path → stroke or fill
ctx.beginPath();
ctx.arc(200, 100, 40, 0, Math.PI * 2);
ctx.fill();
// Text
ctx.font = "20px Verdana";
ctx.fillText("Hello", 20, 200);
// Image
const img = new Image();
img.src = "logo.png";
img.onload = () => ctx.drawImage(img, 0, 0, 64, 64);
Useful state methods
| Method | What it does |
|---|---|
ctx.save() / ctx.restore() | Stack the entire state — colours, transforms, clip. |
ctx.translate / rotate / scale | Move, spin, resize the coordinate system. |
ctx.clearRect(x, y, w, h) | Erase a rectangle. |
ctx.clip() | Limit future drawing to the current path. |
ctx.globalCompositeOperation | Blend modes — "multiply", "screen", etc. |
An animation loop
JS
let x = 0;
function tick() {
ctx.clearRect(0, 0, 400, 300);
ctx.fillStyle = "#04AA6D";
ctx.fillRect(x, 100, 40, 40);
x = (x + 2) % 400;
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
High-DPI displays
JS
const ratio = window.devicePixelRatio || 1; canvas.width = 400 * ratio; canvas.height = 300 * ratio; canvas.style.width = "400px"; canvas.style.height = "300px"; ctx.scale(ratio, ratio); // draw in CSS pixels, crisp on retina
Tip: For pure rendering performance, batch
fillStyle/strokeStyle changes — setting them every shape is the most common slowdown in Canvas code.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Canvas!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Get the 2D rendering context.
const ctx = canvas.
('2d');
Two words concatenated.
Discussion
Loading…