从下往上动画d3图形

时间:2013-11-19 08:00:01

标签: javascript animation d3.js

我正在尝试在加载时从x轴开始制作d3条形图。到目前为止,这是我的代码:

$(document).ready(function(){
                        setTimeout(function(){
                    var t = 0, // start time (seconds since epoch)
                        v = 70, // start value (subscribers)
                        data = d3.range(4).map(next); // starting dataset

                    function next() {

                        return {
                            value: v = dataArray[t].length,
                            time: ++t
                        };
                    }

                    var w = 30,
                        h = 80;

                    var x = d3.scale.linear()
                        .domain([0, 1])
                        .range([0, w]);

                    var y = d3.scale.linear()
                        .domain([0, 100])
                        .rangeRound([0, h]);

                    var barPadding = 5;

                    var chart = d3.select("#revenue").append("svg")
                        .attr("class", "chart")
                        .attr("width", w * data.length + (data.length-1)*8)
                        .attr("height", h);

                    var rects = chart.selectAll("rect")

                        .data(data)
                        .enter().append("rect")

                        .attr("x", function(d, i) { return i*35; })
                        .attr("y", function(d) { return h - y(d.value) - .5; })
                        .attr("width", w)
                        .attr("fill", "white")
                        .attr("height", function(d) { return 0; });

                    rects.data(data)

                        .transition().duration(2000).delay(200)
                        .attr("height", function(d) { return y(d.value); })
                        .attr("y", function(d) {return h-y(d.value); });
                    },2000);
                    });

我知道答案在于同时为Y位置设置动画,以便它呈现出向上成长的外观,但无论我改变什么,我都无法从下往上制作动画。

1 个答案:

答案 0 :(得分:2)

            graph.selectAll("rect")
                  .append("animate")
                  .attr("attributeName","y")
                  .attr("attributeType","XML")
                  .attr("begin","0s")
                  .attr("dur","1s")
                  .attr("fill","freeze")
                  .attr("from",yaxis_offset)
                  .attr("to",function(d){return yscale(d.value);} );

          graph.selectAll("rect")
                  .append("animate")
                  .attr("attributeName","height")
                  .attr("attributeType","XML")
                  .attr("begin","0s")
                  .attr("dur","1s")
                  .attr("fill","freeze")
                  .attr("from",0)
                  .attr("to",function(d){return yaxis_offset-yscale(d.value);});

这个代码对我有用,可以像你说的那样为条形图设置动画......根据你的需要改变变量..