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/6938788 to your computer and use it in GitHub Desktop.
Save eweitnauer/6938788 to your computer and use it in GitHub Desktop.
SVG Semantic Zooming

A series of related examples:

Using

d3.transition().duration(0).each('end', function() {
    circle.attr("transform", transform);
});

instead of directly calling

circle.attr("transform", transform);

making the animation look smoother on my mobile devices, since it will be rendered inside an animationFrame and only as often as the browser can handle it, instead of every time an event comes in.

Compare to M. Bostock's example.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoom + Pan</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
svg {
font: 10px sans-serif;
}
.overlay {
fill: none;
pointer-events: all;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<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(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 svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.call(d3.behavior.zoom().x(x).y(y).scaleExtent([1, 8]).on("zoom", zoom));
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height);
var circle = svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("r", 2.5)
.attr("transform", transform);
function zoom() {
d3.transition().duration(0).each('end', function() {
circle.attr("transform", transform);
});
}
function transform(d) {
return "translate(" + x(d[0]) + "," + y(d[1]) + ")";
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment