JSFiddle - React, Tailwind, and code Playground
HTML
<div id="main">
<h1>D3 "Geometric Zooming" grid</h1>
<div class="intgraph" />
</div>
CSS
line.grid {
fill: none;
stroke: #9ecae1;
stroke-width: 1.5px;
}
svg {
border: solid 1px gray;
padding:2em;
}
JavaScript
var w = 400,
h = 400,
gridSpacing = 10;
/*** Configure zoom behaviour ***/
var zoomer = d3.behavior.zoom()
.scaleExtent([0.1,10])
//allow 10 times zoom in or out
.on("zoom", zoom);
//define the event handler function
function zoom() {
console.log("zoom", d3.event.translate, d3.event.scale);
vis.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")"
);
}
/** Initialize SVG ***/
var graph = d3.select(".intgraph").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("class", "graph")
.call(zoomer); //Attach zoom behaviour.
// Add a transparent background rectangle to catch
// mouse events for the zoom behaviour.
// Note that the rectangle must be inside the element (graph)
// which has the zoom behaviour attached, but must be *outside*
// the group that is going to be transformed.
var rect = graph.append("rect")
.attr("width", w)
.attr("height", h)
//.style("fill", "none")
//make transparent (vs black if commented-out)
.style("pointer-events", "all");
//respond to mouse, even when transparent
var vis = graph.append("svg:g")
.attr("class", "plotting-area");
//create a group that will hold all the content to be zoomed
/*** Draw grid lines ***/
var vLines = vis.selectAll("lines.vertical")
.data( d3.range(0,w+1,gridSpacing) );
//d3.range(start,stop,step) returns an array of numbers
//counting from start up to (but not including) stop
//skiping "step" value in between each number
//ie. for gridSpacing = 10, this will return [0,10,20,30...]
//until w
vLines.enter().append("line")
.attr("class", "vertical grid");
vLines.attr("x1", function(d){return d;})
.attr("y1", 0)
.attr("x2", function(d){return d;})
.attr("y2", h);
var hLines = vis.selectAll("lines.horizontal")
.data(...