首页 > 解决方案 > d3 - 实现回放

问题描述

这个问题在 d3 v5 上。

我正在尝试在使用 d3 的固定持续时间内实现多个同步转换,但关键帧数据来自数组中的用户数据,而不是 d3 插值。(编辑)换句话说,我试图实现基于数据的重播,而不是插值转换。

我试着把这个问题写成下面的例子。

var arr1=d3.range(0,1000), arr2=d3.range(0,10000),
  one=d3.select("#one"), two=d3.select("#two");

var duration=5000; // 5 seconds

// TBD:
// Synchronously Update "one" and "two" continously with the individual values of 
// arr1 and arr2 respectively for a total duration of "duration"
// 
// Obviously "two" should be updated faster than "one" during the duration
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="one">Update arr1 here</div>
<div id="two">Update arr2 here</div>

canvas在我的实际用例中,我必须同步更新许多图表(每个图表都是自己绘制的)。不必在 d3 中执行此操作,但我认为鉴于 d3 可以通过插值一次处理多个转换,必须有一些东西可以解决这个问题。

标签: javascriptd3.js

解决方案


如果您想像条形图一样为 div 设置动画,这里有一个临时解决方案:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        div {
            width: 0%;
            min-height: 10px;
        }
    </style>
</head>
<body>
<div id="one"></div>
<div id="two"></div>

<button onClick="update()">update</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script>
var arr1=d3.range(0,1000), arr2=d3.range(0,10000),
one=d3.select("#one"), two=d3.select("#two");

var duration=5000; // 5 seconds

function update() {
    one.style("transition", "width " + (duration/1000) + "s")
        .style("background", "blue")
        .style("width", (arr1.pop()/9) + "px");
    two.style("transition", "width " + (duration/1000) + "s")
        .style("background", "blue")
        .style("width", (arr2.pop()/9) + "px");
}

// TBD:
// Synchronously Update "one" and "two" continously with the individual values of 
// arr1 and arr2 respectively for a total duration of "duration"
// 
// Obviously "two" should be updated faster than "one" during the duration
</script>
</body>
</html>

推荐阅读