当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Add two different svg element in g element of svg using d3.js from a dataset

问题描述:

I want to add one circle and one text element to every group element of the svg based on the dataset, similar to the below one.

var dataset=[1,4];

<g>

<circle cx="100" cy="100" r="20" fill="blue"></circle>

<text x="100" y="100" fill="white">Hello World</text>

</g>

<g>

<circle cx="100" cy="100" r="20" fill="blue"></circle>

<text x="100" y="100" fill="white">Hello World</text>

</g>

here below my working sample code.

var svgSelection2=d3.select("#div-svg2").append("svg")

.attr("width",900)

.attr("height",500)

.style("background-color","lightgreen");

var dataset=[1,4];

var group=svgSelection2.selectAll("g")

.data(dataset2)

.enter()

.append("g");

var circles=group.selectAll("circle")

.data(dataset)

.enter()

.append("circle")

.attr("cx",function(d,i){ return d*100 ;})

.attr("cy",100)

.attr("r",function(d,i){ return d*20;})

.attr("fill","blue");

var textElement=group.selectAll("text")

.data(dataset)

.enter()

.append("text")

.attr("x",function(d,i){return d*100;})

.attr("y",100)

.text("Hello World")

.attr("fill","white");

This code append two circles and two elements to every group element.

Thanks in advance

网友答案:

You don't need to enter the same dataset again, so you can do this

var svgSelection2=d3.select("#div-svg2").append("svg")
        .attr("width",900)
        .attr("height",500)
        .style("background-color","lightgreen");

var dataset=[1,4];
var group=svgSelection2.selectAll("g")
        .data(dataset)
        .enter()
        .append("g");

var circles = group.append("circle")
        .attr("cx",function(d,i){ return d*100 ;})
        .attr("cy",100)
        .attr("r",function(d,i){ return d*20;})
        .attr("fill","blue");

var textElement=group.append("text")
        .attr("x",function(d,i){return d*100;})
        .attr("y",100)
        .text("Hello World")
        .attr("fill","white");
分享给朋友:
您可能感兴趣的文章:
随机阅读: