gpt4 book ai didi

svg - D3 : Select and alter external SVG?

转载 作者:行者123 更新时间:2023-12-04 18:09:44 24 4
gpt4 key购买 nike

是否可以在 Adob​​e Illustrator 中创建的嵌入(外部)SVG 中选择和更改元素?

html:

<object data="circles.svg" type="image/svg+xml" id="circles"></object>

圈子.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):
var svg = document.getElementById('circles');

但是如何在 D3 中解析和更改?
额外问题:调试 D3 选择器的最佳方法?

最佳答案

这实际上是一个令人讨厌的情况,因为您不能直接在嵌入的文档上使用 DOM 选择器。原则上你需要的选择器是"#circles > circle" ,但这在这种情况下不起作用。所以你需要一些相当丑陋的东西

var my_circles = d3.select(document.getElementById("circles").contentDocument)
.selectAll("circle");

我发现 Javascript 控制台对于调试选择器非常有用。只需输入您要测试的内容,然后查看是否返回了您想要的内容。

问题是上述代码仅在对象加载后才起作用。即使使用类似 JQuery 的 .ready()将不足以确保这一点。一个快速而肮脏的解决方案是反复检查元素是否存在,直到它们:
function changeColor() {
var sel = d3.select(document.getElementById("circles").contentDocument)
.selectAll("circle");
if(sel.empty()) {
setTimeout(changeColor, 100);
} else {
sel.attr("fill", "black");
}
}
changeColor();

完整示例 here .

关于svg - D3 : Select and alter external SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com