Skip to content

Instantly share code, notes, and snippets.

@pkerpedjiev
Forked from mbostock/.block
Last active May 3, 2017 16:03
Show Gist options
  • Save pkerpedjiev/16d34341a50c037e72513b35cbba9e3d to your computer and use it in GitHub Desktop.
Save pkerpedjiev/16d34341a50c037e72513b35cbba9e3d to your computer and use it in GitHub Desktop.
Canvas Geometric Zooming
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoom + Pan</title>
<style>
.overlay {
fill: none;
pointer-events: all;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var randomX = d3.random.normal(width / 2, 80),
randomY = d3.random.normal(height / 2, 80);
var data = d3.range(20000).map(function() {
return [
randomX(),
randomY()
];
});
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height)
.call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
.node().getContext("2d");
draw();
function zoom() {
canvas.save();
canvas.clearRect(0, 0, width, height);
canvas.translate(d3.event.translate[0], d3.event.translate[1]);
canvas.scale(d3.event.scale, d3.event.scale);
draw();
canvas.restore();
}
function draw() {
var i = -1, n = data.length, d;
canvas.beginPath();
while (++i < n) {
d = data[i];
canvas.moveTo(d[0], d[1]);
canvas.arc(d[0], d[1], 2.5, 0, 2 * Math.PI);
}
canvas.fill();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment