2014-05-22 73 views
1

如何使用D3.js動態更改線條插值?如何動態更改線條插值

I.e.爲什麼下面的D3.js示例中的「切換」按鈕不會更新插值,我該如何解決?

jsfiddle

<!DOCTYPE html> 
<head> 
    <script type="text/javascript" src="http://d3js.org/d3.v2.js"></script> 
    <style> 
     svg {width: 200px; height: 200px; border: 1px solid gray;} 
     .line { fill: none; stroke: steelblue; stroke-width: 2;} 
    </style> 

</head> 
<body> 
    <button id="toggle">Toggle</button><br/> 
    <svg></svg> 
</body> 

<script type="text/javascript"> 

document.getElementById('toggle').onclick=function(){ 
    if (chart.interpolate === 'basis') { 
     chart.interpolate = 'linear'; 
    } else { 
     chart.interpolate = 'basis'; 
    } 
    chart.render(); 
}; 

function Chart() { 
    this.svg = d3.select('svg'); 

    this.points = [{x:0, y:60}, {x:50, y:110}, {x:90, y:70}, {x:140, y:100}]; 

    this.interpolate = 'basis'; 

    this.line = d3.svg.line() 
        .x(function(d){return d.x;}) 
        .y(function(d){return d.y;}) 
        .interpolate(this.interpolate); 

    this.render = function (container) { 
     this.svg.append('path') 
      .attr('d', this.line(this.points)) 
      .attr('class', 'line'); 
    }; 
} 

chart = new Chart(); 
chart.render("#chart"); 

</script> 
</html> 

回答

1

的問題是,line不會重新創建或render函數內部更新,因此它保持舊的插值值。

function Chart() { 
    this.svg = d3.select('svg'); 

    this.points = [{x:0, y:60}, {x:50, y:110}, {x:90, y:70}, {x:140, y:100}]; 

    this.interpolate = 'basis'; 

    this.line = d3.svg.line() 
        .x(function(d){return d.x;}) 
        .y(function(d){return d.y;}) 
        .interpolate(this.interpolate); 

    this.render = function (container) { 

     this.svg.selectAll('path.line').remove() 

     // update the line with the new interpolate value 
     this.line.interpolate(this.interpolate); 

     this.svg.append('path') 
      .attr('d', this.line(this.points)) 
      .attr('class', 'line'); 
    }; 
} 

這是在行動上jsfiddle