thatOneGuy
thatOneGuy

Reputation: 10622

How to translate SVG and all its children

I have been playing with this fiddle : https://jsfiddle.net/thatOneGuy/8k8ggpcn/4/

Majority of it is not my code, but from line 330-345 I have added, tried to, the ability to move the SVG by a certain amount. But this is not working. I can't seem to figure out why.

I have tried using D3. So added an ID of mainSVGContainer to the SVG at the start :

svg = d3.select("#svg1")
    .append("svg").attr('id', 'mainSVGContainer')

And used this to translate :

 d3.select('#mainSVGContainer').style('fill','blue').attr("transform", "translate(0 "+difference +")")

Difference is an integer worked out before this call, its around 130. But this doesn't seem to work. It gets written to the DOM but doesn't look like it's affecting the SVG.

I have tried with vanilla JavaScript :

var svgContainer = document.getElementById('mainSVGContainer');
 svgContainer.offsetLeft = 1000;

This doesn't work either

And I have tried with inline JS to alter the styling :

 svgContainer.style.left = 1000;

Still no luck. I presumed it was due to it being an SVG element but I tried doing the same with the container of this SVG which was a div and no luck.

Any ideas ?

Upvotes: 0

Views: 897

Answers (1)

thatOneGuy
thatOneGuy

Reputation: 10622

As JSBob and others from the following :

I found out Chrome, along with other browsers, don't support the translation of SVG elements. So, as a work around, I appended a g element to the SVG and translated that :

Appending g :

 svg = d3.select("#svg1") 
    .append("svg").attr("height", h)
    .attr("width", w)
    .append('g')
    .attr('id', 'mainSVGContainer')
    .attr("height", h)
    .attr("width", w)
    .attr("class", "graph-svg-component")

Translating g :

d3.select('#mainSVGContainer').transition().duration(1000).attr("transform", "translate(0 "+(-difference) +")")

Added the transition so you can see before and after :)

Updated fiddle : https://jsfiddle.net/thatOneGuy/8k8ggpcn/7/

Upvotes: 1

Related Questions