Skip to content

Instantly share code, notes, and snippets.

@eweitnauer
Last active February 12, 2018 15:53
Show Gist options
  • Save eweitnauer/6940142 to your computer and use it in GitHub Desktop.
Save eweitnauer/6940142 to your computer and use it in GitHub Desktop.
SVG Semantic Zooming
<!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(100).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 text = svg.selectAll("text")
.data(data)
.enter().append("text")
.text(function() {return Math.round(Math.random()*10)})
.style('font-size', '30px')
.style('font-style', 'italic')
.attr("transform", transform);
function zoom() {
text.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