1

I have successfully implemented some code from this D3 example of animated line drawing but I'm none the wiser as to how it works. I would really appreciate a line by line breakdown of how the code works. I'm relatively new to D3; I understand the basics of DOM manipulation with the library, but I feel this requires an intermediate level of understanding which I lack.

I have included below the specific part of the example which I have reengineered. I suspect the clever part is tied up in the .attr("stroke-dashoffset", 0); & .attr("stroke-dashoffset", totalLength); parts so a clear explanation of how these work and how they contribute to the effect would be very appreciated.

var totalLength = path.node().getTotalLength();

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

svg.on("click", function(){
  path      
    .transition()
    .duration(2000)
    .ease("linear")
    .attr("stroke-dashoffset", totalLength);
})

Many thanks in advance

opalenzuela
  • 3,139
  • 21
  • 41
Jeshua
  • 363
  • 1
  • 3
  • 15
  • how did you solve this? – fuxes Apr 25 '16 at 19:46
  • 1
    The concept is explained well visually in this CSS tricks post: https://css-tricks.com/svg-line-animation-works/ I don't have the D3 implementation to hand, but here's an implementation using HTML5 canvas https://stackoverflow.com/questions/25442709/draw-html5-javascript-canvas-path-in-time/25446101#25446101 – Jeshua Apr 26 '16 at 11:01

1 Answers1

2

Interesting side effect. Anyway, the dasharray and dashoffset SVG properties: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset.

As far as I got what it does:

  1. Initilize the path dash pattern as totallength visible, and totallength non visible
  2. Set the dashoffset to be totallength first, making only the gap part visible
  3. Transition to dashoffset to 0, making only the dash part visible.
  4. On click, again transit to totallength dash offset, making again only the gap part visible.

Just for play, change the setting of the dasharray: .attr("stroke-dasharray", totalLength/2 + " " + totalLength/2)

hsilomedus
  • 211
  • 1
  • 4
  • Jake Archibald has a very good animated explanation: http://jakearchibald.com/2013/animated-line-drawing-svg/ – Ray Shan Feb 23 '14 at 02:03