Canvas in JavaScript
Introduction
The <canvas> element provides a bitmap drawing surface for charts, games, image filters, and signatures. You draw with a 2D or WebGL rendering context from JavaScript. This chapter focuses on 2D basics—enough to understand how animation and data visualization libraries start.
Prerequisites
Setup Canvas
<canvas id="board" width="320" height="200"></canvas>
<script>
const canvas = document.getElementById("board");
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("2d context not supported");
ctx.fillStyle = "#1e293b";
ctx.fillRect(0, 0, canvas.width, canvas.height);
</script>width / height attributes set drawing buffer pixels (distinct from CSS size).
Draw Shapes and Text
// Rectangle and circle
ctx.fillStyle = "#3b82f6";
ctx.fillRect(20, 20, 100, 60);
ctx.beginPath();
ctx.arc(200, 80, 40, 0, Math.PI * 2);
ctx.fillStyle = "#f97316";
ctx.fill();
// Text
ctx.fillStyle = "#fff";
ctx.font = "16px sans-serif";
ctx.fillText("Hello Canvas", 20, 120);Stroke and Paths
ctx.beginPath();
ctx.moveTo(10, 160);
ctx.lineTo(300, 160);
ctx.strokeStyle = "#94a3b8";
ctx.lineWidth = 2;
ctx.stroke();Clear and Animate
function frame(t) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const x = (t / 10) % canvas.width;
ctx.fillStyle = "#22c55e";
ctx.fillRect(x, 90, 30, 30);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);Use requestAnimationFrame instead of setInterval for smooth animation.
Pixel Data (Brief)
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// manipulate imageData.data (RGBA bytes)
ctx.putImageData(imageData, 0, 0);Mini Example: Simple Bar Chart
const values = [30, 80, 45, 60];
const barWidth = 40;
const gap = 20;
const max = Math.max(...values);
ctx.fillStyle = "#64748b";
values.forEach((v, i) => {
const h = (v / max) * (canvas.height - 40);
const x = 20 + i * (barWidth + gap);
const y = canvas.height - 20 - h;
ctx.fillStyle = "#3b82f6";
ctx.fillRect(x, y, barWidth, h);
});For production charts, use Chart.js, ECharts, or D3.
FAQ
Canvas vs SVG?
Canvas is pixel-based (good for games/dense pixels); SVG is DOM vectors (good for accessible icons and CSS styling).
Retina displays?
Scale with devicePixelRatio and set canvas buffer size larger—otherwise drawings look blurry.
WebGL?
getContext("webgl2") for 3D and GPU shaders—separate advanced track.