D3.js:暂停按钮不起作用(在用于动画的回调函数中)

时间:2016-11-01 23:02:00

标签: javascript animation d3.js

我正在尝试添加暂停和恢复动画的功能: enter image description here

它显示了火车(黄色)在一条线上的位置。我的数据是嵌套的,其中键是时间段。它目前每render(t)毫秒调用interval函数。 我已经阅读了this guidethis question,但我仍然对如何将其应用于我的案例感到迷茫。

我想暂停动画,检查火车属性,然后恢复它。 任何帮助表示赞赏!

currentTime = 0;
interval = 100;
var trainsHolder = svg.append('g')

 function render(t){

    trains = trainsHolder
            .selectAll('circle')
            .data(nested_train_data[t], function(d){ return d.car_id})

    // enter
    trains
        .enter()
        .append("circle")
        .each(setAttributes)

    // update
    trains
        .transition()
        .duration(interval)
        .each(setAttributes)

    // exit
    trains.exit().remove();

    // update timer
    timer_holder
        .select("text")
        .transition()
        .duration(interval)
        // .text("Time : " + String(t/60))
        .text(String(nested_train_data[t][0].Date.getHours()) + ":"  + String( nested_train_data[t][0].Date.getMinutes()))

    };

render(currentTime);

var callback = function () {
        return function () {
// my time increments are 60 seconds

            currentTime = currentTime + 60; 
            // console.log(currentTime);
            if (currentTime <= maxTime) {
                render(currentTime);
                d3.timer(callback(), interval);
            }
            return true;
        }
    }



    d3.timer(callback(), interval);
// NOT WORKING
$("#pauseBtn").click(function() {
        trainsHolder.selectAll('circle').transition().duration( 0 );
      });

1 个答案:

答案 0 :(得分:1)

从图片中取出“暂停”,动画是否正常运行?如果是这样,问题似乎与您的回调函数有关。这就是驱动动画的原因。

您需要以下内容。基本思路是,当且仅当模拟没有暂停并且未超过maxTime时才推进动画计时器:

return function(elapsed) {
    paused = getPausedState();
    //use the elapsed time to set instead of a fixed interval, so the animation plays at a constant rate
    //only advance the animation timer if the simulation is not paused
    //and we haven't exceeded the max
    nextTime = paused || currentTime > maxTime ? currentTime : currentTime + elapsed;
    render(nextTime);
    d3.timer(callback(), interval);