D3:选择和更改外部SVG? [英] D3: Select and alter external SVG?
问题描述
是否可以选择和修改在Adobe Illustrator中创建的嵌入(外部)SVG中的元素?
Is it possible to select and alter elements in an embedded (external) SVG , created in Adobe Illustrator?
html:
<object data="circles.svg" type="image/svg+xml" id="circles"></object>
circles.svg:
circles.svg:
<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="100px" >
<circle id="c_red" fill="#A00" stroke="#000" cx="40" cy="40" r="40"/>
<circle id="c_grn" fill="#0A0" stroke="#000" cx="60" cy="60" r="40"/>
</svg>
d3代码:
<script>
var my_circles = d3.select("#circles svg").selectAll("circles");
my_circles.attr("fill", "black");
</script>
否则,我可以采用其他方法。例如,像这样的东西可能工作选择(确实找到SVG):
Otherwise, I'm open to other ways of doing this. For example, something like this might work to select (which does indeed locate the SVG):
var svg = document.getElementById('circles');
但是如何解析和改变D3?
奖金问题:调试D3选择器的最佳方法?
But how to then parse and alter in D3? Bonus question: best way to debug D3 selectors?
推荐答案
这实际上是一个令人讨厌的情况, t直接在嵌入文档上使用DOM选择器。原则上,您需要的选择器是#circles> circle
,但在这种情况下不会工作。所以你需要的东西比较丑陋像
This is actually a nasty case, because you can't use DOM selectors directly on embedded documents. In principle, the selector you need is "#circles > circle"
, but this won't work in this case. So you need something rather ugly like
var my_circles = d3.select(document.getElementById("circles").contentDocument)
.selectAll("circle");
我发现Javascript控制台对于调试选择器非常有用。只需键入你想测试的东西,看看你想要的东西是否返回。
I find the Javascript console quite useful for debugging selectors. Just type in what you want to test and see if the things you want are returned.
问题是上面的代码只有在对象被加载后才能工作。即使使用类似JQuery的 .ready()
也不足以确保。一个快速和肮脏的解决方案是反复检查元素是否存在直到它们是:
The problem is that the above code only works once the object has been loaded. Even using something like JQuery's .ready()
won't be sufficient to ensure that. A quick and dirty solution is to repeatedly check whether the elements are present until they are:
function changeColor() {
var sel = d3.select(document.getElementById("circles").contentDocument)
.selectAll("circle");
if(sel.empty()) {
setTimeout(changeColor, 100);
} else {
sel.attr("fill", "black");
}
}
changeColor();
完整示例此处。
这篇关于D3:选择和更改外部SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!