Skip to content

Instantly share code, notes, and snippets.

@tomeustace
Created January 5, 2017 16:18
Show Gist options
  • Save tomeustace/fc9d558583dabaced76e2539a52a9d91 to your computer and use it in GitHub Desktop.
Save tomeustace/fc9d558583dabaced76e2539a52a9d91 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis path {
display: none;
}
.axis line {
stroke-opacity: 0.3;
shape-rendering: crispEdges;
}
.view {
fill: url(#gradient);
stroke: #000;
}
</style>
<h3>d3 v4 Zoom Experimentation</h3>
<p>Use d3.event.transform.rescaleX to rescale circle elements. </p>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [14,20,35,40,50,67,72,79,87];
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var zoom = d3.zoom()
.translateExtent([[-100, -100], [width + 90, height + 100]])
.on("zoom", zoomed);
var x = d3.scaleLinear()
.domain([10, 90])
.range([-1, width + 1]);
var xAxis = d3.axisBottom(x)
.ticks((width + 2) / (height + 2) * 10)
.tickSize(height)
.tickPadding(8 - height);
var view = svg.append("rect")
.attr("class", "view")
.attr("x", 0.5)
.attr("y", 0.5)
.attr("width", width - 1)
.attr("height", height - 1);
var circles = svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.style('fill','blue')
.attr('r',15)
.attr('cx', function(d) {
return x(d);
})
.attr('cy', function(d) {
return d * 5;
});
var gX = svg.append("g")
.attr("class", "axis axis--x")
.call(xAxis);
svg.call(zoom);
function zoomed() {
var rescale = d3.event.transform.rescaleX(x);
gX.call(xAxis.scale(rescale));
d3.selectAll('circle').each(function(d) {
d3.select(this).attr("cx", rescale(d));
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment