Skip to content

Instantly share code, notes, and snippets.

@eweitnauer
Forked from mbostock/.block
Last active December 25, 2015 07:19
Show Gist options
  • Save eweitnauer/6938973 to your computer and use it in GitHub Desktop.
Save eweitnauer/6938973 to your computer and use it in GitHub Desktop.
Canvas Semantic Zooming
<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoom + Pan</title>
<style>
.overlay {
fill: none;
pointer-events: all;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://graspingmath.com/libs/css-fpsmeter.js"></script>
<!--<div id="fps"></div>-->
<script>
//// measure fps using css transitions
//var fps_el = document.getElementById("fps");
//document.addEventListener('fps', function(evt) { fps_el.innerHTML = evt.fps + " fps"}, false);
//FPSMeter.run(0.5);
var width = 960,
height = 500;
var randomX = d3.random.normal(width / 2, 80),
randomY = d3.random.normal(height / 2, 80);
var data = d3.range(2000).map(function() {
return [
randomX(),
randomY()
];
});
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, height])
.range([height, 0]);
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height)
.call(d3.behavior.zoom().x(x).y(y).scaleExtent([1, 8]).on("zoom", zoom))
.node().getContext("2d");
draw();
function zoom() {
canvas.clearRect(0, 0, width, height);
draw();
}
function draw() {
var i = -1, n = data.length, d, cx, cy;
canvas.beginPath();
while (++i < n) {
d = data[i];
cx = x(d[0]);
cy = y(d[1]);
canvas.moveTo(cx, cy);
canvas.arc(cx, cy, 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