Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active October 20, 2022 11:58
Show Gist options
  • Save mbostock/3680958 to your computer and use it in GitHub Desktop.
Save mbostock/3680958 to your computer and use it in GitHub Desktop.
Canvas Geometric Zooming
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var canvas = d3.select("canvas").call(d3.zoom().scaleExtent([1, 8]).on("zoom", zoom)),
context = canvas.node().getContext("2d"),
width = canvas.property("width"),
height = canvas.property("height");
var randomX = d3.randomNormal(width / 2, 80),
randomY = d3.randomNormal(height / 2, 80),
data = d3.range(2000).map(function() { return [randomX(), randomY()]; });
draw();
function zoom() {
var transform = d3.event.transform;
context.save();
context.clearRect(0, 0, width, height);
context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);
draw();
context.restore();
}
function draw() {
var i = -1, n = data.length, d;
context.beginPath();
while (++i < n) {
d = data[i];
context.moveTo(d[0], d[1]);
context.arc(d[0], d[1], 2.5, 0, 2 * Math.PI);
}
context.fill();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment