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

标签 javascript animation d3.js

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

它显示了火车(黄色)在一条线上的位置。我的数据是嵌套的,其中关键是时间段。目前,它每 interval 毫秒调用一次 render(t) 函数。 我读过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 );
      });

最佳答案

去掉图片中的“暂停”,动画是否正常运行?如果是这样,问题似乎出在您的回调函数上。这就是动画的驱动力。

你想要类似下面的东西。基本思想是,当且仅当模拟未暂停且未超过 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);

关于javascript - D3.js:暂停按钮不起作用(在用于动画的回调函数中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369953/

相关文章:

javascript - JQuery 动画后元素恢复到原始大小

javascript - Three.js 在对象上添加按钮以显示有关该位置的信息

html - 标签未显示在 D3 圆环图上

javascript - react : Trying to render props that populate AFTER render

JavaScript 显示/隐藏为 div 列表的过滤器

css - svg, Canvas 在一起而不使用绝对位置

javascript - D3 mousedown事件删除错误节点

javascript - 在 NodeJs 中,为什么新的 Date 构造函数将默认时间设置为上午 7 点?

javascript - 想通过javascript计算同一项目中目录中的文件

javascript - 使用 Javascript 从输入框值中获取总和,带小数