【问题标题】:D3.js: Pause button not working (in a callback function used for animation)D3.js:暂停按钮不起作用(在用于动画的回调函数中)
【发布时间】:2016-11-03 05:37:16
【问题描述】:

我正在尝试为我的动画添加暂停和恢复功能:

它显示了火车(黄色)在一条线上的位置。我的数据是嵌套的,关键是时间段。它目前每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 );
      });

【问题讨论】:

    标签: javascript animation d3.js


    【解决方案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);
    

    【讨论】:

    • 谢谢!动画确实有效,我就是无法暂停。所以,我的理解是你改变了回调函数的内部函数(即elapsed)。但是有两个问题: 1. 如何获取经过的时间 2. 如何使用参数调用回调的内部函数(在 d3.timer()... 中)? (如你所见,我是新手!)
    • 当 D3 给您回电时,应自动将经过的时间交给您(请参阅 D3 文档)。内部函数是 callback() 返回的内容,D3 将为您调用它。
    • 我搞砸了可能是因为它没有显示,但文件在那里
    • 您在 simVisMap.js 中有 JS 错误 Uncaught ReferenceError: queue is not defined 并且您尚未定义 getPausedState() 例程。你需要这样写,以便paused 获得一个有效值:)
    • 好吧,队列是这样的:github.com/d3/d3-queue另一个我不知道该怎么做!
    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2013-06-29
    • 2016-06-09
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    相关资源
    最近更新 更多