DEV Community

Seed Map
Seed Map

Posted on

Pan and Zoom on a Canvas Map With Pointer Events (Zooming Around the Cursor)

Interactive maps feel simple to use and are surprisingly fiddly to build: drag to pan, wheel or pinch to zoom, and the zoom should happen around the cursor, not the top-left corner. This post builds that behaviour on a plain <canvas> with pointer events, no libraries, in about 80 lines. The same approach works for game maps, floor plans or large images.

The camera model

Keep a tiny camera object: an offset in world units and a scale.

const camera = { x: 0, y: 0, scale: 1 };

const worldToScreen = (wx, wy) => [
  (wx - camera.x) * camera.scale,
  (wy - camera.y) * camera.scale,
];

const screenToWorld = (sx, sy) => [
  sx / camera.scale + camera.x,
  sy / camera.scale + camera.y,
];
Enter fullscreen mode Exit fullscreen mode

Everything else is built on these two functions.

Drawing

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

function draw() {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.setTransform(camera.scale, 0, 0, camera.scale,
                   -camera.x * camera.scale, -camera.y * camera.scale);
  drawWorld(ctx); // your tiles, markers, grid...
}
Enter fullscreen mode Exit fullscreen mode

Using setTransform means drawWorld can work in world coordinates and never think about the camera.

Panning with pointer events

Pointer events cover mouse, pen and touch with one API.

let dragging = null;

canvas.addEventListener('pointerdown', e => {
  canvas.setPointerCapture(e.pointerId);
  dragging = { x: e.clientX, y: e.clientY };
});

canvas.addEventListener('pointermove', e => {
  if (!dragging) return;
  camera.x -= (e.clientX - dragging.x) / camera.scale;
  camera.y -= (e.clientY - dragging.y) / camera.scale;
  dragging = { x: e.clientX, y: e.clientY };
  requestAnimationFrame(draw);
});

canvas.addEventListener('pointerup', () => { dragging = null; });
Enter fullscreen mode Exit fullscreen mode

Dividing by camera.scale keeps the map glued to the cursor at any zoom level.

Zooming around the cursor

The trick: remember which world point is under the cursor before zooming, then move the camera so the same point is still under the cursor afterwards.

canvas.addEventListener('wheel', e => {
  e.preventDefault();
  const rect = canvas.getBoundingClientRect();
  const sx = e.clientX - rect.left;
  const sy = e.clientY - rect.top;

  const [wx, wy] = screenToWorld(sx, sy);
  const factor = Math.exp(-e.deltaY * 0.0015);
  camera.scale = Math.min(32, Math.max(0.05, camera.scale * factor));

  camera.x = wx - sx / camera.scale;
  camera.y = wy - sy / camera.scale;
  requestAnimationFrame(draw);
}, { passive: false });
Enter fullscreen mode Exit fullscreen mode

Using Math.exp on deltaY makes zoom speed consistent across mice and trackpads, which report very different deltas.

Sharp rendering on high-DPI screens

function resize() {
  const dpr = window.devicePixelRatio || 1;
  canvas.width = canvas.clientWidth * dpr;
  canvas.height = canvas.clientHeight * dpr;
  ctx.scale(dpr, dpr);
  draw();
}
window.addEventListener('resize', resize);
resize();
Enter fullscreen mode Exit fullscreen mode

If you do this, remember to include dpr in the transform inside draw() as well.

Only draw what is visible

For big worlds, compute the visible world rectangle and skip anything outside it:

const [left, top] = screenToWorld(0, 0);
const [right, bottom] = screenToWorld(canvas.clientWidth, canvas.clientHeight);
Enter fullscreen mode Exit fullscreen mode

Then loop over tiles between left..right and top..bottom only. This keeps panning smooth even when the world is millions of units wide.

Seeing it in a real app

This is the same interaction model used by tile-based game maps. An online Minecraft seed explorer is a good example of the finished feel: drag, scroll to zoom around the cursor, and tiles appear only where you are looking.

Next steps

  • Pinch-to-zoom: track two active pointers and use the change in distance between them as the zoom factor.
  • Inertia: keep the last drag velocity and decay it over a few frames after pointerup.
  • Keyboard: arrow keys to pan and +/- to zoom, for accessibility.

Top comments (0)