简体   繁体   中英

Set attribute of circle from another circle's attribute using d3.select?

I want to place an SVG circles around some SVG circles. I find the desired circles using d3.selectAll().filter() . This almost works--a circle gets created. But I can't figure out how to set the center of the new circle from the center of the old circle, so the new circle is created at 0,0. Nothing I've tried has worked.

// first I find the circles I want
foundNodeCircles = d3.selectAll(".node").filter(function(d,i){return d.label == nodeRE;});

// Then I create a new, larger circle for each circle that I found:
svg.selectAll(".nodeHighlightRing")
.data(foundNodeCircles)  // make one ring per node circle
.enter().append("circle") // make the ring
.attr("class", "nodeHighlightRing") // specify its qualities
.attr("cx", function(d) { return d.cx;}) // BROKEN: set center to center of old circle
.attr("cy", function(d) { return d.cy;}) // BROKEN: set center to center of old circle
.attr("r", 10)
.style("opacity", 0)
.style("stroke", "green")
.style("stroke-width", "1.5")
.style("stroke-opacity", "1");

In in addition to d.cx , I've tried this.cx , d.attr["cx"] , this.attr["cx"] , d3.select(this).attr("cx") , d3.select(d).attr("cx") , and a few other things that seemed less likely to work. None were successful.

I thought that this question or this one would help, but I am apparently doing something different.

The problem is that your variable foundNodeCircles is holding a d3 selection, and the data-joining method .data() expects an array representing your data.

If you instead use foundNodeCircles[0] for your data join you will be referring to the array of elements that were contained in the selection, rather than the selection itself. Then, when you are setting your attributes, d will refer to the DOM element itself, so you can either use a d3 selection to select d and call .attr to retrieve the attribute, or simply use the DOM method .getAttribute .

svg.selectAll(".nodeHighlightRing")
  // BIND TO THE ELEMENTS RATHER THAN THE SELECTION
  .data(foundNodeCircles[0])
  .enter().append("circle")
  .attr("class", "nodeHighlightRing")
  // EITHER OF THESE METHODS SHOULD WORK
  .attr("cx", function(d) { return d3.select(d).attr("cx"); })
  .attr("cy", function(d) { return d.getAttribute("cy"); })
  // ... etc. ...

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