1

I've got a very intricate path defined with the standard SVG pen markup ("M 130 30", "L 132, 40", etc). How do I take this markup and create a path so I can draw the entire path slowly as described here?: Can't make paths draw growing slowly with D3

Community
  • 1
  • 1
victor
  • 6,688
  • 9
  • 44
  • 48

1 Answers1

4

The approached listed in duopixel's answer in that question still works even if the <path> node to be animated was not generated by D3. Here is a modified version of duopixel's code using an existing SVG path node:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
    <svg xmlns="http://www.w3.org/2000/svg" id="visualization" height="300" width="700">
        <path id="existingLine" fill="none" stroke-width="2" stroke="steelblue" 
        d="M0,45.355864964297126Q56,93.30709264413157,70,101.42710214950955C91,113.60711640757651,119,112.60236634997189,140,126.5559600180769S189.00000000000003,192.28891292428457,210.00000000000003,194.45105993687628S259,143.07483109253366,280,140.97027343535498S329,190.98168538928422,350,180.42067555568514S399.00000000000006,58.614334097794526,420.00000000000006,70.56354121136098S469.00000000000006,240.5996349725512,490.00000000000006,260.08205631279486S539,201.70472761196623,560,200.44635014631868S609,277.9853193478483,630,251.69287320847783Q644,234.16457578223088,700,25.163375883849042">
        </path>
    </svg>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script type="text/javascript">
    // select the already-existing path node via its ID.
    var path = d3.select("#existingLine");

    // from here forward the code is exactly like the original....
    var totalLength = path.node().getTotalLength();

    path
      .attr("stroke-dasharray", totalLength + " " + totalLength)
      .attr("stroke-dashoffset", totalLength)
      .transition()
        .duration(2000)
        .ease("linear")
        .attr("stroke-dashoffset", 0);

  </script>
</body>
</html>

Or, if you do want to use D3 for the creation of the node, just take your existing path string and use it in place of the line() function call. Again, adapting duopixel's code:

var path = svg.append("path")
  .attr("d", "M 130 30", "L 132, 40") // and so on
  .attr("stroke", "steelblue")
  .attr("stroke-width", "2")
  .attr("fill", "none");
Community
  • 1
  • 1
explunit
  • 18,967
  • 6
  • 69
  • 94
  • So this seems to draw all lines at the same time. I'd like it to draw it in the order that it's specified in the path - drawing one line at a time. Can I do that with this code? Specifically, it seems like all M actions run at time=0, not one after the other. – victor Jul 06 '13 at 03:34
  • Actually, I think I'll move this to another question, as it is now not related to this... – victor Jul 06 '13 at 19:17