Skip to content

Instantly share code, notes, and snippets.

@nponeccop
Forked from mbostock/.block
Last active June 30, 2016 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nponeccop/e3a9203036dd68b3a1f9433e8200a647 to your computer and use it in GitHub Desktop.
Save nponeccop/e3a9203036dd68b3a1f9433e8200a647 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: url(#gradient);
stroke: #000;
}
</style>
<svg width="960" height="500">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0.0%" stop-color="#2c7bb6"></stop>
<stop offset="12.5%" stop-color="#00a6ca"></stop>
<stop offset="25.0%" stop-color="#00ccbc"></stop>
<stop offset="37.5%" stop-color="#90eb9d"></stop>
<stop offset="50.0%" stop-color="#ffff8c"></stop>
<stop offset="62.5%" stop-color="#f9d057"></stop>
<stop offset="75.0%" stop-color="#f29e2e"></stop>
<stop offset="87.5%" stop-color="#e76818"></stop>
<stop offset="100.0%" stop-color="#d7191c"></stop>
</linearGradient>
</defs>
</svg>
<script src="//d3js.org/d3.v4.0.0-alpha.50.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 view = svg.append("rect")
.attr("class", "view")
.attr("x", 0.5)
.attr("y", 0.5)
.attr("width", width - 1)
.attr("height", height - 1);
var gX = svg.append("g")
.attr("class", "axis axis--x")
.call(xAxis);
var gY = svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.call(d3.zoom()
.scaleExtent([1, 40])
.translateExtent([[-100, -100], [width + 90, height + 100]])
.on("zoom", zoomed));
var newZoom = null;
var rx = null;
var ry = null;
var draw = drawProc(function () {
view.attr("transform", newZoom);
gX.call(xAxis.scale(rx));
gY.call(yAxis.scale(ry));
})
function zoomed() {
var z = d3.event.transform.toString();
if (z != newZoom) {
rx = d3.event.transform.rescaleX(x);
ry = d3.event.transform.rescaleY(y);
newZoom = z;
draw();
}
}
function drawProc(f) {
var requested = false;
return function () {
if (!requested) {
requested = true;
d3.timeout(function (time) {
requested = false;
f(time);
});
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment