Jquery 读入并操作多个外部SVG文件
我有几个外部SVG文件和各种形状,它们是我想要呈现的路径和多边形。对于每个形状,我希望以随机位置和不同的笔划颜色呈现它们 我可以使用d3.xml一次成功地读入一个,更改其属性,等等Jquery 读入并操作多个外部SVG文件,jquery,svg,d3.js,Jquery,Svg,D3.js,我有几个外部SVG文件和各种形状,它们是我想要呈现的路径和多边形。对于每个形状,我希望以随机位置和不同的笔划颜色呈现它们 我可以使用d3.xml一次成功地读入一个,更改其属性,等等 var sampleSVG = d3.select("body") .append("svg") .attr("width", 300) .attr("height", 300); var shapes = ["https://dl.dropboxusercontent.com/u/24
var sampleSVG = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var shapes = ["https://dl.dropboxusercontent.com/u/2467665/shapes-24.svg",
"https://dl.dropboxusercontent.com/u/2467665/shapes-23.svg"];
d3.xml("https://dl.dropboxusercontent.com/u/2467665/shapes-24.svg", "image/svg+xml",
function(xml) {
sampleSVG.node().appendChild(xml.documentElement);
var innerSVG = sampleSVG.select("svg");
innerSVG
.select("*")//selects whatever the shape is, be it path or polygon
.attr("transform", "translate("+Math.floor(Math.random() * 100)+","+Math.floor(Math.random() * 100)+") scale(.3)")
.attr("stroke", "purple");
});
从阵列中读取多个外部文件的最佳方式是什么?如何独立操作每个文件的位置和属性?您可以使用D3.js作者提供的库等待所有文件返回,然后再渲染导入的svg。见下面的例子
变量宽度=300,高度=300;
var sampleSVG=d3.selectbody
.appendsvg
.attr{width:width,height:height};
变量形状=[
{url:https://dl.dropboxusercontent.com/u/2467665/shapes-24.svg,颜色:'紫色'},
{url:https://dl.dropboxusercontent.com/u/2467665/shapes-23.svg,颜色:'红色'}
];
var q=队列;
shapes.forEachfunctionshape{
q、 deferd3.xml、shape.url、image/svg+xml;
};
q、 awaitAllfunctionerror,结果{
示例VG.选择所有“g.shape”。数据形状
//g标记用于将形状定位在随机位置
.enter.append'g'.attr'class',shape'
.attr'transform',函数{
返回“translate”+Math.random*width-50+,“+Math.random*height-50+
}
.每一个功能,我{
//然后将加载的svg文件追加到g标记中
此.appendChildresults[i].documentElement;
d3.选择这个。选择“svg”。选择*
.attrtransform,scale0.2
.attrstroke,函数{返回d.color;};
}
};
是否有一种方法可以单独编辑每个形状,比如为每个形状设置不同的笔划颜色?很好,谢谢-这些形状是否被视为一类对象。加载后我可以选择并进一步操作的形状,例如sampleSVG.selectAll.shape.transition.attrstroke,黑色;要将它们全部变为黑色[请注意,这不起作用],必须使选择器如下所示:sampleSVG.selectAll.shape svg*.transition.attrstrow,黑色;嗯,当我在awaitAll函数之后添加它时,这似乎不起作用-这里是JSFiddle:我们离原来的问题越来越远了,但是。。。您不能将它放在awaitAll函数之外,因为它将以错误的顺序执行。waitall代码的执行是异步的,具体取决于文件从请求返回的时间。