使用d3.js在几个div创建一个SVG [英] Using d3.js to create an SVG at several divs
问题描述
假设我有一些HTML看起来像:
< html>
< body>
< div class =a>< / div>
...
< div class =a>< / div>
...
< div class =a>< / div>
...
< / body>
< html>
其中...只是段落或其他代码。
问题:我想能够使用d3.js在每个div上附加一个SVG。
例如,我想创建一个矩形:
var svg =((SOMETHING GOES HERE!))
.append(svg)
.attr(width,w)
.attr ;
var sep = svg.selectAll(rect)
.append(rect)
.attr(x,0)
.attr y,0)
.attr(width,100)
.attr(height,10)
如何使用第一行的选择器来做到这一点?我尝试了
$ pselectall()
和select()
与各种div.a,。
解决方案你可以将SVG附加到你的div:
d3.selectAll(div.a)append(svg)
pre>
如果你想选择并操作那些SVG后,你只需添加一个子选择:
d3.selectAll(div.a)。select(svg)。append(rect)。attr(height,50).attr ,50)
或者,您可以对SVG进行分类,并在做出选择后进行选择:
d3.selectAll(div.a)append(svg)。attr(class,divSVG)
pre>
d3.selectAll(svg.divSVG).append(rect)。attr(height,50).attr(width,50)
此外,如果您希望它们出现在您的
元素之前,请使用insert而不是append:
d3.selectAll(div.a)。insert(svg,p)
Suppose I have some HTML which looks like:
<html> <body> <div class = "a"></div> ... <div class = "a"></div> ... <div class = "a"></div> ... </body> <html>
where the ...'s are just paragraphs or other code.
Problem: I'd like to be able to use d3.js to append an SVG at each of these div's.
For example, let's say I want to make a rectangle like:
var svg = ((SOMETHING GOES HERE!)) .append("svg") .attr("width", w) .attr("height", h); var sep = svg.selectAll("rect") .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 100) .attr("height", 10)
How can I use the selectors on the first line to do this? I've tried
selectall()
andselect()
with various "div.a", ".", etc., things, but nothing seems to work.解决方案You can just append the SVG to your div with:
d3.selectAll("div.a").append("svg")
And if you want to select and act upon those SVGs after you made them just add a sub-select:
d3.selectAll("div.a").select("svg").append("rect").attr("height", 50).attr("width", 50)
Or you could class your SVGs and select them after you made them:
d3.selectAll("div.a").append("svg").attr("class", "divSVG") d3.selectAll("svg.divSVG).append("rect").attr("height", 50).attr("width", 50)
Also, if you want them to appear before your
elements, use insert instead of append:
d3.selectAll("div.a").insert("svg", "p")
这篇关于使用d3.js在几个div创建一个SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!