Skip to content

Instantly share code, notes, and snippets.

@mbostock mbostock/.block forked from mbostock/.block
Last active Jan 31, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.