D3.js Transitions

孤街醉人 提交于 2019-11-30 08:22:58

Because the origin of the coordinate system is from the top-left, the 'y' value is anchored at the top of each bar. If the 'y' value is fixed, and the 'height' is increased, it looks like the bars grow down. In order to make the bars grow from the bottom, you'll need to transition both the 'y' and the 'height' at the same time.

This should be what you're looking for, I've only changed two lines.

chart.selectAll("rect")
 .data(data)
 .enter().append("rect")
 .attr("x", function(d, i) { return x(i) - .5; })
 .attr("y", function(d) { return h - .5; })                  //new----
 .attr("width", w)
 .transition().delay(function (d,i){ return i * 300;})
 .duration(300)
 .attr("height", function(d) { return y(d.value); })
 .attr("y", function(d) { return h - y(d.value) - .5; });    //new-----

I've started the 'y' value at the bottom of the chart (h - 0.5). Then when you transition, you increase the 'height' (y(d.value)) and decrease the 'y' (h - y(d.value)) at the same rate. This has the effect of fixing the bottom of the bar to the axis.

Hope this helps!

Remember the x-scale is backwards to what you would expect (bars have to be built upwards from the bottom (where bottom = svg height). Use Transition to animate bars on enter.

An example of what I think you are trying to achieve can be found here: http://bl.ocks.org/jamesleesaunders/f32a8817f7724b17b7f1

All the best,

Jim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!