Starting Transitions and Animations With Area Grap

2019-04-11 21:33发布

问题:

I want to have the area graph "draw" itself at the start of the program from left to right. I already have one line in my graph doing this, however I cannot get the area under the line to correctly animate, or "draw" itself when the page first boots up. Currently, this is what I have for my area.

var area = d3.svg.area()
    .x(function(d) {return xScale(d.date); })
    .y0(line_chart_height)
    .y1(function(d) {return yScale(d.close); });

line_chart.append("path")
    .datum(data)
    .attr("class", "area")
    .attr("d", area)

I can get the area up there fine and draw the line fine, but I can't make it so that when the page first loads the area will essentially "draw" itself from left to right like a line would in this example, EXCEPT from left to right, not right to left.

Any help is appreciated, I've tried using the following and it hans't worked for me.

.datum(data)
.transition().duration(2500)
.attr("d", area)

Thanks in advance, Sam

回答1:

Consider using an svg clipPath, i.e.:

svg.append("clipPath")
    .attr("id", "rectClip")
  .append("rect")
    .attr("width", 0)
    .attr("height", height);

Then, you can simulate the drawing of the items by transitioning the clipping path on page load:

d3.select("#rectClip rect")
  .transition().duration(3000)
    .attr("width", width);

Here is an example jsfiddle: http://jsfiddle.net/qAHC2/688/.