繁体   English   中英

我无法让d3过渡到使用requestAnimationFrame

[英]I can't get d3 transition to work with requestAnimationFrame

我正在组织一个测试程序来学习d3.js. 但是我似乎无法过渡到工作。 我已经多次阅读过文档,无法弄清楚我做错了什么。

我假设这与使用转换和requestAnimationFrame有关,但没有搜索术语的组合为我提供了有用的答案。 谁能告诉我哪里出错了?

        (function(){
        "use strict";
        var randArray = [];

        (function randomWalk(){
            for(var i=0;i<5;i++) randArray[i] = Math.round(Math.random() * 10) % 2? randArray[i]+1 || Math.round(Math.random() * 10) : randArray[i]-1 || Math.round(Math.random() * 10);
            setTimeout(randomWalk,800);
        })();

        (function update(){
            var d3 = window.d3 || {},
                mySelection = d3.select("div#container").selectAll("div").data(randArray);
                mySelection.enter().append("div").text(function(d){return ""+d;});
                mySelection.text(function(d){return ""+d;}).transition().style('padding-bottom',function(d,i){return (d*2.5)+'em'});

            requestAnimationFrame(update);
        })();

    })();

这是一个jsfiddle: http//jsfiddle.net/Racheet/bPfFY/

你几乎拥有它! 你发布的小提琴错过了'transition()'之前的一段时间:

mySelection.enter().append("div")
   .text(function(d){return ""+d;})
   .transition().style('padding-bottom',function(d,i){return (d*2.5)+'em'});

更新小提琴: http//jsfiddle.net/bPfFY/2/

目前,页面加载时只有一个转换。 如果你希望每半秒更改一次条,你需要在调用update时更新randArray的值。

编辑:阅读完评论后,我更新了小提琴http://jsfiddle.net/bPfFY/3/

我改变了一些尝试让它工作的东西,但基本上'.enter()'仅在从'.data()'向页面添加元素时使用。 当我们第二次调用update时,div已经存在并且'.enter()'选择中没有任何内容(更多内容如下: http ://bost.ocks.org/mike/join/)

当调用update()时,我们应该只选择已存在的div元素,更新它们的数据值并使用新值来重绘文本和填充:

d3.select("div#container")
        .selectAll("div").data(randArray)
    .text(function(d){return ""+d;})
        .transition().duration(500)
    .style('padding-bottom', function(d, i){return (d*2.5 + 'px');});   

我还将requestAnimationFrame(update)更改为setTimeout(update,1000)。 d3不链接动画,所以通常最好确保一个完成(使用'.duration(500)')然后再启动另一个动画。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM