[英]Append defs tag and use it within SVG in D3.js
I am grouping 3 circles together within defs
tags so they can be seen in an SVG
. 我将3个圆圈分组在
defs
标记中,以便可以在SVG
看到它们。 I have been also been recommended to use the use
tag so I can see this shape that is defined within defs
and recreate it anywhere within the SVG
. 还建议我使用
use
标签,以便可以看到在defs
定义的此形状,并在SVG
任何位置重新创建它。 I am creating them and appending them to data using D3.js
. 我正在创建它们,并使用
D3.js
将它们附加到数据中。 However, My problem is when I use the use
tag, it seems to me that I am creating a new SVG every time I want to display the shape that is in the defs
tag. 但是,我的问题是,当我使用
use
标签时,每次我想显示defs
标签中的形状时,似乎都在创建一个新的SVG。 My questions are: Is there anyway to use the defs
tag without using the use
tag? 我的问题是:是否仍然可以使用
defs
标签而不使用use
标签? The second question is: How can I display that shape within the defs
tag many times within only one SVG
without creating an SVG
every time. 第二个问题是:如何仅在一个
SVG
在defs
标签中多次显示该形状,而不必每次都创建SVG
。 Here is my code: 这是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
</head>
<body>
<div id ="mainSVG">
<svg id = "packSVG" width = "1160" height = "620" style = "outline: thin solid black"
version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id= "mySymbol">
<circle cx="200" cy="70" r="25" fill="red" />
<circle cx="170" cy="80" r="20" fill="red" />
<circle cx="230" cy="80" r="20" fill="red" />
</symbol>
</defs>
</svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var dataset = [20, 60, 90, 120];
var display = d3.select("body").select("#mainSVG").select("#packSVG").selectAll("use")
.data(dataset).enter().append("use")
.attr("xlink:href","#MySymbol")
.attr("transform", function (i) { i+=50; return "translate(" + i + "," + i + ")";});
</script>
</body>
</html>
Could anyone please help with this issue? 有人可以帮助解决这个问题吗? Thank you very much in advance.
提前非常感谢您。
You can define the circle group using using g element as shown below and there is no need for creating multiple svg. 您可以使用g元素定义圆组,如下所示,并且无需创建多个svg。 JSFiddle
JSFiddle
HTML 的HTML
<svg id="mainSVG" width="600" height="500">
<defs>
<g id="mySymbol">
<circle cx="200" cy="70" r="25" fill="red" />
<circle cx="170" cy="80" r="20" fill="red" />
<circle cx="230" cy="80" r="20" fill="red" />
</g>
</defs>
</svg>
Javascript code JavaScript代码
var dataset = [20, 60, 90, 120];
var display = d3.select("body")
.select("#mainSVG")
.selectAll("use")
.data(dataset)
.enter()
.append("use")
.attr("xlink:href","#mySymbol")
.attr("transform", function (i) { i+=50; return "translate(" + i + "," + i + ")";});
Note that there typo in your code. 请注意,您的代码中有错别字。 The id
mySymbol
is misspelled as MySymbol
while creating use elements. 创建use元素时,id
mySymbol
拼写为MySymbol
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.