Reputation: 137
I've gone through a few posts as to how to zoom to an element within a larger SVG that has a zoom and pan function on its own as well, but without any luck. I have a large map where you can zoom and pan to elements manually which works but i want it to zoom and pan to any element itself when clicked on such an element. I can't seem to get the right values for the transformation.
Here's a jsfiddle of what i've got so far: http://jsfiddle.net/1gyjd2xt/1/
var svg = d3.select("#svg-container svg");
var container = svg.select("#container");
zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([1, 10])
.on("zoom", zoomed);
svg.call(zoom);
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
d3.selectAll(".text").on("click", function () {
var t = d3.transform(d3.select(this).attr("transform")),
x = t.translate[0],
y = t.translate[1];
console.log(x);
console.log(y);
var scale = 10;
//Zoom to element
//svg.transition()
//.call(zoom
//.translate( calculate X, calculate Y)
//.scale(scale).event);
});
Upvotes: 3
Views: 6277
Reputation: 137
Ok, I managed to find the right coordinates. I just have to call the zoom again and use the X
and Y
.
I got from the text element and then it zooms with the object being in the top left corner because that's where the origin of your view is.
So, if I then add the height
and width
of my view divided by 2, then I have the zoom in the center. Using the zoom behavior
, it won't mess up my standard zoom and pan with the mouse, and always uses the current X
and Y
to zoom to my clicked element.
svg.transition().duration(3000)
.call(zoom.translate([((x * -scale) + (svgWidth / 2)), ((y * -scale) + svgHeight / 2)])
.scale(scale).event);
Here's an updated fiddle: http://jsfiddle.net/1gyjd2xt/4/
Upvotes: 3