John Abraham
John Abraham

Reputation: 18801

Animate the drawing of a curve in D3

I've made a simple bezier curve in d3. I would like to animate the curve from: starting point to end point. I would like the animation to take 1.25s?

JSFiddle

html

<div id="myelement">  
</div>

js:

var svg = d3.select('#myelement').append('svg'),
    curve = svg.append('path')
                 .attr('d', 'M0,200 C400,200 400,200 400,0')
                 .attr('stroke', '#fff')
                    .attr('fill-opacity', 0);

curve.transition()
       .attr('d', 'M0,200 C400,200 400,200 400,0')

Upvotes: 1

Views: 1581

Answers (1)

Leo
Leo

Reputation: 2135

Here's a pretty cool way of animating a curve that I saw in an answer to another question https://stackoverflow.com/a/13354478/151212. With your situation the code would look something like the following:

var svg = d3.select('#myelement').append('svg'),
    curve = svg.append('path')
               .attr('d', 'M0,200 C400,200 400,200 400,0')
               .attr('stroke', '#000')
               .attr('fill-opacity', 0);

var length = curve.node().getTotalLength();

curve.attr("stroke-dasharray", length + " " + length)
     .attr("stroke-dashoffset", length)
     .transition()
       .duration(1250)
       .attr("stroke-dashoffset", 0);

JSFiddle

Upvotes: 2

Related Questions