I needed to add zoom/pan on d3.js visualisation. After a painful search on Google, I finally found a simple way to do it.
d3.js has everything to do it with only a few lines of code.
You just need to create a g
element as first child of the SVG element and connect d3.behavior.zoom()
behavior.
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.behavior.zoom().on("zoom", function () {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")
}))
.append("g")
That's it!
Now you can add all SVG node to that g
view port element.
There is a live example here: http://bl.ocks.org/sgruhier/1d692762f8328a2c9957
Update for v4
For d3v4 it's even simpler, no more d3.behavior.zoom()
behavior.
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
}))
.append("g")
There is a live example here https://bl.ocks.org/sgruhier/50990c01fe5b6993e82b8994951e23d0
I added .on("dblclick.zoom", null) just before the .append('g') to disable doubleclick zoom