Monolisky
Monolisky

Reputation: 43

SVG returns to its default scale and position after initializing it with specific scale and position

I'm trying to initialize svg by setting its scale and position with a specific value and it works but the problem appears when users try to scale or drag svg, it immediately returns back to its default scale and position as you can see in this JSFiddle Example (try to zoom or drag the svg to see the problem), if there is a way to set d3.event.scale and d3.event.translate properties but it seems that these properties are read only. Here is my code:

var scale=0.5,translate=[25,800];

var svg = d3.select("svg");
var g = svg.select("g");

svg.attr("width", "100%")
   .attr("height", "100%")
   .attr('viewBox', '0 0 1200 1200').attr("preserveAspectRatio", "xMidYMid 
meet").call(d3.behavior.zoom().on("zoom", function() {
     g.attr("transform", "translate(" + translate + ")" + " scale(" + scale + 
     ")");
     scale = d3.event.scale;
     translate =  d3.event.translate;
 }));

 g.attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")");

Upvotes: 2

Views: 96

Answers (1)

bumbeishvili
bumbeishvili

Reputation: 1460

This answer refers d3.v3 version, in v4 we would use d3.zoomIdentity

You need to pass translate and scale value to the zoom function and you also need to translate g element initially

var g = svg.select("g")
           .attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")")

Relevant Snippet

svg.attr("width", "100%")
    .attr("height", "100%")
    .attr('viewBox', '0 0 1200 1200').attr("preserveAspectRatio", "xMidYMid meet")
    .call(d3.behavior.zoom()
        .translate(translate)    // ADDED THIS
        .scale(scale)            // AND THIS
        .on("zoom", function () {
            scale = d3.event.scale;
            translate = d3.event.translate;
            g.attr("transform", "translate(" + translate + ")" + " scale(" + scale + ")");
        }));

Check out updated JSFiddle

Upvotes: 2

Related Questions