Search code examples
d3.jsdatamaps

datamaps - dashed animated arc


Help,

I'm using datamaps to create a world map and I have solid line arcs going from point to point. They're animated so they get drawn on page. However try as I might I can't find a way to make the arcs dashed so that the animation appears like the dashed line is moving in a direction from point to point. I can't find an example of this anyway, I want to give the illusion of movement, of data flowing continuously from one point to another along an arc. Is this even possible in datamaps? Are there examples out there? I must be googling the wrong thing as I'm coming up short on answers.


Solution

  • You can implement this feature using CSS animations.

    var svg = d3.select("body")
      .append("svg")
      .attr("width", 500).attr("height", 400);
    
    var x = d3.scale.linear().domain([0, 10]).range([0, 700]);
    var y = d3.scale.linear().domain([0, 10]).range([10, 290]);
    
    var data = d3.range(50).map(function() {
      return Math.random() * 10
    })
    var line = d3.svg.line()
      .interpolate("cardinal")
      .x(function(d, i) {
        return x(i);
      })
      .y(function(d) {
        return y(d);
      });
    
    var path = svg.append("svg:path").attr("d", line(data));
     #line {
       width: 100%;
       margin: 20px 0;
       height: 300px;
       background: #eee;
     }
     
     path {
       stroke: steelblue;
       stroke-width: 1;
       fill: none;
       stroke-dasharray: 10;
       animation: dash 5s linear infinite;
       animation-direction: reverse;
     }
     
     @keyframes dash {
       to {
         stroke-dashoffset: 1000;
       }
     }
     
     button {
       margin: 20px 0 0 20px;
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>