简体   繁体   中英

create position / and add text in circle using D3 using “g” and svg in JavaScript /or Coffee

so I am trying to seperate each cicle to look something like this

![enter image description here][1]

here 在此处输入图片说明

but with the text inside , but I couldnt' figure it out how my circle would not spread out as I use this coffescript code below

svg_w = 800
svg_h = 400
svg = d3.select("body").append("svg").attr("width", svg_w).attr("weight", svg_h)

list = [1,2,3,4,5]
dataset = (x*10 for x in list)
console.log dataset


nodes = svg.append("g").attr("class", "nodes").selectAll("circle")
        .data(dataset).enter().append("g")
            .attr("transform", (d, i) ->

                  d.x = i * 70 + 50
                  d.y = svg_h / 2

                  "translate(" + d.x + "," + d.y + ")"

                )

nodes.append("circle").attr("class", "node").attr "r", 20
nodes.append("text").attr("text-anchor", "middle").text (d) ->d.name

My result show all my circle to upper left coner

在此处输入图片说明

Any suggestion ?

Thanks

The problem is that you're trying to set properties ( dx and dy ) on a number instead an object. This doesn't work and your translation is undefined. Use separate variables instead, eg

 dx = i * 70 + 50
 dy = svg_h / 2
 "translate(" + dx + "," + dy + ")"

The text doesn't show up because you're referencing a property .name that doesn't exist. Also, black text on a black circle isn't visible. You can fix this easily by giving the text a different color and appending the number as the text:

nodes.append("text").attr("text-anchor", "middle").text (d) ->d

Complete example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM