This question pertains to the same topic as a previously asked and answered one:
- D3.js - how to add zoom button with the default wheelmouse zoom behavior
I have attempted to implement the code found in this link http://bl.ocks.org/linssen/7352810.
The reason for seeking help here is that the solutions provided are based on D3.js version 3, which do not effectively address my issue. Below is my current implementation for zooming.
let translateVar = [0,0];
let scaleVar = 1;
function create_pan_zoomable_svg() {
let svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.style("background-color", "#eeeeee")
.call(_zoom).on("dblclick.zoom", null)
.append("g");
d3.select("#zoom_in").on('click', function() { _zoom.scaleBy(svg, 2)});
d3.select("#zoom_out").on('click', function() { _zoom.scaleBy(svg, 0.5)});
return svg;
}
var _zoom = d3.zoom()
.on("zoom", function() {
translateVar[0] = d3.event.transform.x;
translateVar[1] = d3.event.transform.y;
scaleVar = d3.event.transform.k;
svg.attr('transform', 'translate(' + translateVar[0] + ',' + translateVar[1] + ') scale(' + scaleVar + ')');
});
In trying to solve my problem, I came across this post d3.js V4 Button Zoom Implementation acting weird. However, adapting the code only resulted in the buttons working but not the wheelmouse-based zoom. Below is the adapted code from that post.
function create_pan_zoomable_svg() {
let zoom = d3.zoom().on("zoom", zoomed);
let svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.style("background-color", "#eeeeee")
.append("g").call(zoom).on("dblclick.zoom", null);
d3.select("#zoom_in").on("click", function() {
zoom.scaleBy(svg.transition().duration(750), 1.2);
});
d3.select("#zoom_out").on("click", function() {
zoom.scaleBy(svg.transition().duration(750), 0.8);
});
return svg;
}
function zoomed() {
svg.attr("transform", d3.event.transform);
}
One issue I encountered was that if I were to place the append("g")
after calling the zoom
, both types of zoom would work but fail to track translation accurately.
To further analyze the problem, please refer to: https://jsfiddle.net/vxhuzyp2/5/
Your assistance in resolving this matter would be greatly appreciated.