我一直在玩这个 fiddle :https://jsfiddle.net/thatOneGuy/8k8ggpcn/4/
其中大部分不是我的代码,但从第 330-345 行开始,我尝试添加了将 SVG 移动一定量的功能。但这是行不通的。我似乎不明白为什么。
我尝试过使用D3。因此,在 SVG 开头添加了 mainSVGContainer
ID:
svg = d3.select("#svg1")
.append("svg").attr('id', 'mainSVGContainer')
并用它来翻译:
d3.select('#mainSVGContainer').style('fill','blue').attr("transform", "translate(0 "+difference +")")
Difference
是在此调用之前计算出的一个整数,大约为 130。但这似乎不起作用。它被写入 DOM,但看起来并不影响 SVG。
我尝试过使用普通 JavaScript:
var svgContainer = document.getElementById('mainSVGContainer');
svgContainer.offsetLeft = 1000;
这也不起作用
我尝试使用内联 JS 来改变样式:
svgContainer.style.left = 1000;
还是没有运气。我认为这是因为它是一个 SVG 元素,但我尝试对这个 SVG 的容器做同样的事情,它是一个 div,但没有成功。
有什么想法吗?
最佳答案
作为 JSBob 和其他人,来自以下:
我发现 Chrome 以及其他浏览器不支持 SVG 元素的翻译。因此,作为解决方法,我将一个 g
元素附加到 SVG
中并进行了翻译:
附加 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")
翻译 g :
d3.select('#mainSVGContainer').transition().duration(1000).attr("transform", "translate(0 "+(-difference) +")")
添加了过渡,以便您可以看到之前和之后:)
更新了 fiddle :https://jsfiddle.net/thatOneGuy/8k8ggpcn/7/
关于javascript - 如何翻译 SVG 及其所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938775/