How to split multiple D3 transform commands into separate statements

389 Views Asked by At

I have some trouble with my zooming. I found this zooming with 2x translate and 1x zoom:

g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")");

This is working. But I want to save the zooming state by using zoom commands e.g. So I tried it in the following way:

zoom.translate([width / 2, height / 2]);
zoom.scale(k);
zoom.translate([-x, -y]);
g.transition()
      .duration(750)
      .attr("transform", "translate(" + zoom.translate() + ")scale(" + zoom.scale() + ")");

But in this way zoom.translate([width / 2, height / 2]); is completely ignored because I've overwritten it.

But how can I use the zoom commands to solve my issue?

Another idea

How can I write the both translate statements as one. Is this possible somehow?

Some useful links on this:

1

There are 1 best solutions below

0
On BEST ANSWER

I solved it with the following - very creepy - solution. It's working well but for me it looks very ugly and is based on saving the transformation in a special variable:

var currentzoomy = d3.transform("translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
zoom.scale(currentzoomy.scale[0]);
zoom.translate(currentzoomy.translate);

Is that an OK solution? And maybe someone now has a better idea what my issue was about. =)