This example demonstrates using d3-zoom to drive changes to scales’ domains via transform.rescaleX and transform.rescaleY. The transformed scales are used to draw axes. The transform is also applied via SVG transform to the colorful rainbow rect. (The colors are from Nadieh Bremer’s lovely SVG gradient tutorial.)
-
-
Save juba/ab726357210caa464159101477b0b191 to your computer and use it in GitHub Desktop.
Pan & Zoom Axes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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