Reputation: 4246
I try to make my SVG zoomable in d3.js (version 4).
You can see my attempt here : JSFiddle
HTML
<svg id="mySVG" width="800px" height="600px" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); background: lightgrey;">
<g>
<path d="M 0 0 L 100 0 L 100 20 L 0 20 Z" fill="red"></path>
<path d="M 500 500 L 600 500 L 600 520 L 500 520" fill="green"></path>
</g>
</svg>
JS
$(function() {
var svg = d3.select("#mySVG")
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", "translate(" + d3.event.transform.x + " " + d3.event.transform.y + ") scale(" + d3.event.transform.k + ")");
}));
// For test purposes
//$('#mySVG').css('transform', 'scale(2)');
});
In fact, all seems to work since when I check in the Google's code inspector, focusing on my SVG element, I see the value of translate and scale changing as I mousewheel forward/backward. But nothing happens to the actual element which is very strange since I also tryied to change those scaling/translating value through plain jQuery and the SVG responds by scaling correctly.
Can anyone point me in the right direction for this task ?
For the record, here is the official documentation for the d3.zoom()
function.
Upvotes: 1
Views: 2464
Reputation: 108567
You are applying the attribute transform to your svg
, this is not valid. In your jquery example, you are applying the style transform to your svg
, this is valid. The usual d3
methodology is to wrap your zoomed area in a g
and apply the attribute transform to that. In addition you are missing a comma in your translate:
d3.event.transform.x + " " + d3.event.transform.y //<-- there should be a comma in there
Upvotes: 2
Reputation: 3498
Add an id to your g element, and apply zoom to it rather than the svg root
Upvotes: 1