Skip to content

Instantly share code, notes, and snippets.

Last active August 12, 2019 04:07
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/d1f7b58631e71fbf9c568345ee04a60e to your computer and use it in GitHub Desktop.
Pan & Zoom I
license: gpl-3.0

This example demonstrates using d3-zoom to enable interactive panning and zooming of a Canvas element. The current zoom transform is applied to the Canvas using context.translate and context.scale. This technique is similar to applying an SVG transform. An alternate zooming strategy is to transform the data rather than the view; this lets you customize the display on zoom, such as rendering circles that are the same size regardless of scale.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src=""></script>
var canvas ="canvas"),
context = canvas.node().getContext("2d"),
width ="width"),
height ="height"),
radius = 2.5;
var points = d3.range(2000).map(phyllotaxis(10));
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));
function zoomed() {;
context.clearRect(0, 0, width, height);
context.translate(d3.event.transform.x, d3.event.transform.y);
context.scale(d3.event.transform.k, d3.event.transform.k);
function drawPoints() {
function drawPoint(point) {
context.moveTo(point[0] + radius, point[1]);
context.arc(point[0], point[1], radius, 0, 2 * Math.PI);
function phyllotaxis(radius) {
var theta = Math.PI * (3 - Math.sqrt(5));
return function(i) {
var r = radius * Math.sqrt(i), a = theta * i;
return [
width / 2 + r * Math.cos(a),
height / 2 + r * Math.sin(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment