且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

D3中的转换百分比似乎不起作用

更新时间:2023-11-01 12:29:34

$ b http://jsfiddle.net/8vGm7/6/



风格的组合+清除容器中的先前内容。

  var colors = ['red' 'green','blue','orange','yellow','purple','#ff0','#0ff','#000','#66F']; 
function reload(){
var i = 0,
sum = 0,
newArray = [],
nextVal,
container,
join;

for(i = 0; i nextVal = Math.random();
newArray.push(nextVal);
sum + = nextVal;
}

document.querySelector('#container')。innerHTML ='';
container = d3.select('#container');
join = container.selectAll('div.row')。data(newArray);

join
.enter()
.append('div')
.attr('style',function(d,i){
return'height:0%; background-color:'+ colors [i];
})
.attr('class','row');

join
.transition()
.duration(2000)
.style('height',function(d){
return(100e0 * (d / sum))+'%';
});
}


I'm working on a visualization where I stack rectangles and make them some percentage of the height of the container, but trying to run a transition seems to reset the height of each rectangle to some other value before starting the transition.

I think it's taking the pixel height and accidentally translating it to a percentage. Let's say I set height to 13%, and 13% represents a height of 45px. Let's then say I want to transition it to 10%. When I start the transition, the height jumps to 45% (45px->45%), then rolls to 10%.

I don't know where to look in the D3 code for this. Here's a fiddle showing the behavior: http://jsfiddle.net/8vGm7/

function reload() {
  var newArray = [];
  var i, sum = 0, nextVal;

  for(i = 0; i < 10; i++) {
    nextVal = Math.random();
    newArray.push(nextVal);
    sum += nextVal;
  }

  var container = d3.select('#container');
  var join = container.selectAll('div.row').data(newArray);

  join.enter().append('div').style('height', '0%')
    .style('background-color', function(d,i) {
      return ['red', 'green', 'blue', 'orange', 'yellow', 'purple', '#ff0', '#0ff', '#000', '#66F'][i];
    })
    .attr('class', 'row');

  join.transition().duration(2000)
    .style('height', function(d) {
      return (100e0 * (d / sum)) + '%';
    });
}

Try this out: http://jsfiddle.net/8vGm7/6/

combination of style + clear previous content from the container.

var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'purple', '#ff0', '#0ff', '#000', '#66F'];    
function reload() {
    var i=0, 
        sum = 0, 
        newArray = [],
        nextVal,
        container,
        join;

    for(i = 0; i < 10; i++) {
        nextVal = Math.random();
        newArray.push(nextVal);
        sum += nextVal;
    }

    document.querySelector('#container').innerHTML = '';
    container = d3.select('#container');
    join = container.selectAll('div.row').data(newArray);

    join
    .enter()
    .append('div')
    .attr('style', function(d,i){
        return 'height:0%; background-color: ' + colors[i];
    })
    .attr('class', 'row');

    join
    .transition()
    .duration(2000)
    .style('height', function(d) {
        return (100e0 * (d / sum)) + '%';
    });
}