phantom phantom - 25 days ago 9
Javascript Question

prevent d3 zoom moving text in svg to different position to the rest of the svg

I am using d3 to zoom in on an svg element. There is text on the svg which is then moving to the top left of the screen when I zoom in on the svg. I know this is due to the fact the text has a

transform
property. Does anyone know how to get arrow d this issue.

SVG

<circle id="c-1" class="st6 big-circle" cx="319.4" cy="277" r="26"/>
<text transform="matrix(1 0 0 1 313.3557 284.8708)" class="st1 st7 st8">4</text>


D3/JS

svg = d3.select("svg")
var zoom = d3.behavior.zoom()
.scaleExtent([1, 5])
.on("zoom", function() {
var e = d3.event,
tx = Math.min(0, Math.max(e.translate[0]))
ty = Math.min(0, Math.max(e.translate[1]));
zoom.translate([tx, ty]);
svg.selectAll("*").attr("transform", [
"translate(" + [tx, ty] + ")",
"scale(" + e.scale + ")"
].join(" "));
});
svg.call(zoom);
});

Answer

You could wrap the text element in a g tag...

<circle id="c-1" class="st6 big-circle" cx="319.4" cy="277" r="26"/>
<g>
  <text transform="matrix(1 0 0 1 313.3557 284.8708)" class="st1 st7 st8">4</text>
</g>

And then select everything except the text element to apply the transformation:

svg.selectAll("*:not(text)").attr("transform", [
    "translate(" + [tx, ty] + ")",
    "scale(" + e.scale + ")"
  ].join(" "));
Comments