Courtney Kristensen
Courtney Kristensen

Reputation: 149

D3 initial zoom behavior breaks

Note: (Similar to question here D3.js Set initial zoom level. However their answer is for v3, and the v4 answer in the comment doesn't work.)

I'm trying to setup initial pan/zoom of a d3 animation. As per the answer above, I've setup my SVG zoom with the appropriate translations.

var svg = d3.select("#chart").append("svg")
    .on("touchmove mousemove", moved)
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .call(zoom)
    .append ("g")
    .attr("transform","translate(400,200) scale(.4,.4)");

svg.call(zoom.transform, d3.zoomIdentity.translate(400, 200).scale(0.4))
.call(zoom);

The graph loads fine as intended. However, the initial zooming action breaks the translation/scale, going back to the zoom identity. I have reviewed the docs and numerous zoom examples, but can't pin down this d3 V4 behavior.

Does anyone know what is going on? Feels like a bug.

Upvotes: 3

Views: 1311

Answers (1)

Courtney Kristensen
Courtney Kristensen

Reputation: 149

The following seems to work as desired

var zoom = d3.zoom().on("zoom", zoomed).scaleExtent([1 / 2, 8]);

function zoomed() {
  g.attr("transform", d3.event.transform); // updated for d3 v4
}

var svg = d3.select("#chart").append("svg")
    .on("touchmove mousemove", moved)
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)


var g = svg.append("g");

svg.call(zoom).call(zoom.transform, d3.zoomIdentity.translate(400, 200).scale(0.4));

I'm still not sure what the problem was. Going back to the original code, the transform was correctly applied to g and the transformation erased this without explanation.

One difference is that I define g seperately, maybe that is related.

Upvotes: 3

Related Questions