graph transion

by tyage

HTML

<svg width="400" height="200">
</svg>

<p id="stop">stop</p>
<p id="start">start</p>

JavaScript

var x = d3.scale.linear().domain([0,10]).range([0, 400]);
var y = d3.scale.linear().domain([5,0]).range([0, 200]);
var line = d3.svg.line()
    .x(function(d, i) {return x(i);})
    .y(function(d, i) {return y(d);});

var path;
var timer;
var move = function() {
    timer = setInterval(function() {
        if (path) {
            path.remove();
        }
        path = d3.select('svg')
            .append('path')
            .data([[0,1.2,2,1.4,2,3.2,2.3,1]])
            .attr({
                d: line,
                stroke: 'red',
                fill: 'none'
            });
        
        x = d3.scale.linear().domain([0,10]).range([0, Math.random() * 400]);
        y = d3.scale.linear().domain([5,0]).range([0, Math.random() * 200]);
        path.transition()
            .duration(1000)
            .attr('d', line);
    }, 500);
};
move();

document.getElementById('stop').addEventListener('click', function() {
    clearInterval(timer);
});
document.getElementById('start').addEventListener('click', function() {
    clearInterval(timer);
    move();
});