我已经使用d3.xml()
和queue.js库加载了几个外部SVG文件。我可以操纵的每个文件,因为它是加载使用下面的代码(JSFiddle)(改变它的位置和它的颜色):加载后加载外部XML文件
var width = 300, height = 300;
var sampleSVG = d3.select("body")
.append("svg")
.attr({width: width, height: height});
var shapes = [
{ url: "https://dl.dropboxusercontent.com/u/2467665/shapes-24.svg", color: 'purple' },
{ url: "https://dl.dropboxusercontent.com/u/2467665/shapes-23.svg", color: 'red' }
];
var q = queue();
shapes.forEach(function(shape) {
q.defer(d3.xml, shape.url, "image/svg+xml");
});
q.awaitAll(function(error, results) {
sampleSVG.selectAll('g.shape').data(shapes)
.enter().append('g').attr('class', 'shape')
.attr('transform', function() {
return 'translate(' + Math.random()*(width-50) + ',' + Math.random()*(height-50) + ')'
})
.each(function(d,i) {
this.appendChild(results[i].documentElement);
d3.select(this).select('svg').select("*")
.attr("transform", "scale(0.2)")
.attr("stroke", function() { return d.color; });
})
});
我要访问的形状就像正常D3对象后,他们所有的负载。例如,如上图所示阅读后,我想执行一个简单的过渡,使他们全黑:
sampleSVG.select(".shape svg *").transition().delay(1000).attr("stroke", "black");
但是,这是行不通的。
如何读取这些外部SVG文件,以便像正常一样操作?
您正试图更新q.awaitAll函数之外的颜色。这意味着sampleSVG.select(...)行将在DOM中的形状存在之前运行。尝试在q.awaitAll函数中移动它,就像在http://jsfiddle.net/hk367c5q/中,你应该没问题。 – 2014-10-28 00:06:04
@ BenLyall是的,这有效,但问题是我有很多其他动态的事情正在进行,不涉及这些形状。我希望将所有内容都加载到“引擎盖下”,然后启动动态链,就好像这些是正常的d3生成的形状一样。 – Amyunimus 2014-10-28 00:09:58
当然......这很有道理,你只需要延迟调用sampleSVG.select(...)行,直到完成对DOM的操作。就目前而言,在SVG元素出现之前,你就提前说过了。 – 2014-10-28 00:12:41