我正在尝试使用 D3.js v4 创建时间线。我已经成功地创建了带有轴和画笔的散点图,以允许用户定义特定时间段。
我想让用户能够像音频/视频播放器一样“播放”时间线,该播放器的指示器会使用可自定义的持续时间从左向右移动。为了实现这一点,我放置了一 strip 有过渡的垂直线作为指示器。
我的问题是在转换运行时我无法检索 x 轴坐标。我想实现这一点,因为 x 轴值需要与代码的另一部分进行交互。
我已经尝试了所有方法,包括使用 tween 和 attrTween 函数,但我无法让它工作。理想情况下,我希望指标在画笔限制内开始和停止。
svg.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
svg.append('line')
.attr("class", "timeline-indicator")
.attr("stroke-width", 2)
.attr("stroke", "black")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", height)
.transition()
.duration(9000)
.attr("x1", 500)
.attr("y1", 0)
.attr("x2", 500)
.attr("y2", height);
最佳答案
Andrew's答案很好,而且可能是传统的方法。
但是,出于好奇,这里有一个使用 d3.timer 的替代答案.
当然,数学要复杂一些。另外,请记住耗时是明显的:
The exact values may vary depending on your JavaScript runtime and what else your computer is doing. Note that the first elapsed time is 3ms: this is the elapsed time since the timer started, not since the timer was scheduled.
查看演示:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 100);
var circle = svg.append("circle")
.attr("cx", 30)
.attr("cy", 50)
.attr("r", 20)
.attr("fill", "tan")
.attr("stroke", "dimgray");
var timer = d3.timer(move);
function move(t) {
if (t > 2000) timer.stop();
console.log("position now is: " + ~~(30 + (t / 2000) * 440))
circle.attr("cx", 30 + (t / 2000) * 440)
}
.as-console-wrapper { max-height: 30% !important;}
<script src="https://d3js.org/d3.v4.min.js"></script>
关于javascript - D3.js:在转换运行时检索 x 轴信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640694/