Reputation: 179
I am trying to implement d3 pan and zoom feature. The default pan and zoom works fine, but the requirement is we need zoom in and zoom out buttons as well. I have also implemented zoom button and it works as well. The weird part is when I first move the image and click zoom button the image is moved back to the previous position, not only that when I first zoom with mouse and start zooming again with the button the image scale out to the default and starts zooming again. How do I manage to start zooming from where I transfer from mouse event to button click event.
let imgHeight = 400,
imgWidth = 900,
width = 900,
height = 450;
let zoom = d3.zoom().scaleExtent([1, 8]).on("zoom", zoomed);
let svg = d3.select("#canvas").append("svg")
.attr("width", width + "px")
.attr("height", height + "px");
svg = svg.append("g")
.attr("transform", "translate(0,25)")
.call(zoom)
.append("g");
svg.append("image")
.attr("width", imgWidth + "px")
.attr("height", imgHeight + "px")
.attr("href", "https://www.w3schools.com/howto/img_fjords.jpg");
function zoomed() {
svg.attr("transform", d3.event.transform);
}
let zoomIn = d3.select("#zoom-in");
zoomIn.on("click", function() {
zoom.scaleBy(svg.transition().duration(750), 1.2);
})
<div id='canvas'>
</div>
<div id="tools">
<button id="zoom-in">
+
</button>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 2
Views: 1178
Reputation: 347
You're calling zoom on two different "g" elements, you just need to append once, just remove the second append.
svg = svg.append("g")
.attr("transform", "translate(0,25)")
.call(zoom)
that's why you're experiencing this problem, the zoom function is being applied to nested elements
Upvotes: 2