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

html
<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

Stroke and Paths

javascript
ctx.beginPath();
ctx.moveTo(10, 160);
ctx.lineTo(300, 160);
ctx.strokeStyle = "#94a3b8";
ctx.lineWidth = 2;
ctx.stroke();

Clear and Animate

javascript
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)

javascript
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

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.

What comes next?

Navigation and history.