Increase and decrease radius of a circle using d3

2020-02-12 04:21发布

问题:

I am trying to create a pulse effect on a circle by increasing and decreasing its radius. I would like the circle to grow and shrink based on a given data set. I can only get the transition function to ether increase or decrease the radius but not both.

d3 automatically creates a different circle for each value in the array. How can I make it so that one circle's radius grows and shrinks as it iterates through the array? a simple version of what I have so far is below. Thanks for any help you can offer.

dataset = [30, 80, 150, 90, 20, 200, 180]

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var circle = svg.selectAll("circle")
  .data(dataset)
  .enter()
  .append("circle");

circle
  .attr("cx", 500)
  .attr("cy", h/2)
  .attr("r", dataset[0])
  .attr("fill", "orange");

回答1:

This doesn't really fit with the general D3 data/enter/update/exit pattern because you're not controlling multiple DOM elements, but changing attributes of a single one. You can however do this quite easily with a loop that adds the transitions as specified. The code would look like this.

dataset.forEach(function(d, i) {
    circle.transition().duration(duration).delay(i * duration)
        .attr("r", d);
});

For a complete example, see here.



回答2:

Another option that creates a continuously pulsing circle:

http://bl.ocks.org/chiester/11267307