Search code examples
javascripthtmlcssd3.jsbubble-chart

D3JS oscillating bubbles


This might be trivial to some people, but I am a newbie to D3JS.

I am trying to plot two static bubbles with opacity changing with respect to an array. I am able to plot the bubbles but I can't make their opacity change continuously. I am using transition and delay and the opacity can only change once. Here is my code sample

(function() {

  var dropsize = 100;
  var gapsize = 20;
  var osc = [[1, 1],[0.5, 0.5],[0, 0],[0.5, 0.5],[1, 1],[0.5, 0.5],[0, 0],[0.5, 0.5]];
  var radius = dropsize / 2;
  var h = 100;
  var w = (4 * radius + 3 * gapsize);
  var svg = d3.select("#chart").append("svg");
  var svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .style("background-color", "teal");
  var circles = svg.selectAll("circle")
    .data([radius, 3 * radius])
    .enter()
    .append("circle");
  circles.attr("cx", function(d, i) {
      return d + (i + 1) * gapsize;
    })
    .attr("cy", h / 2)
    .attr("r", function(d, i) {
      return radius;
    })
    .attr("fill", "orange")
    .attr("class", "droplet")
    .attr("id", function(d, i) {
      return "c_" + (i + 1);
    });
  d3.select("#c_1")
    .data(osc)
    .transition().delay(function(d, i) {
      return i * 1000;
    })
    .duration(1000)
    .attr("opacity", function(d) {
      return d[0]
    });
})();

See the Pen Bubble Chart with D3.js using Realtime Data


Solution

  • If by "continuously" you mean that you want to run the transition infinitely, use on("end") to call the transition function again.

    Here is an example:

    var toggle;
    
    var data = [0, 1];
    
    transition();
    
    function transition() {
        toggle ^= 1;
        d3.select("circle")
            .transition()
            .duration(1000)
            .style("opacity", data[toggle])
            .on("end", transition);
    }
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <svg>
    	<circle cx="100" cy="100" r="50"></circle>
    </svg>