如何动态更改行插值

时间:2014-05-22 08:18:58

标签: javascript d3.js

如何使用D3.js动态更改线插值?

即。为什么下面我的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 个答案:

答案 0 :(得分:2)

问题是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

采取行动