Skip to content

Instantly share code, notes, and snippets.

@juba
Forked from mbostock/.block
Last active October 8, 2016 21:45
Show Gist options
  • Save juba/ab726357210caa464159101477b0b191 to your computer and use it in GitHub Desktop.
Save juba/ab726357210caa464159101477b0b191 to your computer and use it in GitHub Desktop.
Pan & Zoom Axes
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis path {
display: none;
}
.axis line {
stroke-opacity: 0.3;
shape-rendering: crispEdges;
}
.zoom {
fill: none;
pointer-events: all;
}
.view {
fill: #FFFFFF;
stroke: #000;
}
</style>
<svg width="960" height="500">
</svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var x = d3.scaleLinear()
.domain([-1, width + 1])
.range([-1, width + 1]);
var y = d3.scaleLinear()
.domain([-1, height + 1])
.range([-1, height + 1]);
var xAxis = d3.axisBottom(x)
.ticks((width + 2) / (height + 2) * 10)
.tickSize(height)
.tickPadding(8 - height);
var yAxis = d3.axisRight(y)
.ticks(10)
.tickSize(width)
.tickPadding(8 - width);
var g = svg.append("g");
var gX = svg.append("g")
.attr("class", "axis axis--x")
.call(xAxis);
var gY = svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
for (i=0; i<=1000; i++) {
tmpx = Math.random() * 900 + 100;
tmpy = Math.random() * 350 + 100;
g.append("circle")
.attr("cx", tmpx)
.attr("cy", tmpy)
.attr("r", 1)
.style("fill", "#FF0000");
}
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.call(d3.zoom()
.on("zoom", zoomed));
function zoomed() {
gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));
gY.call(yAxis.scale(d3.event.transform.rescaleY(y)));
g.attr("transform", d3.event.transform);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment