再次修改这个问题,因为解决方案在新版本的库d3(3.0.3)中不起作用,所以我再次寻求帮助,将不胜感激。
这是库 d3 (3.0.3) 的新代码:
https://gist.github.com/4495104 http://bl.ocks.org/4495104/e7a7589098140dff36df7ab2a824d71072bc3be4
根据我的工作,错误应该在“491”行。
// Reset the domain relative to the current zoom offsets.
x.domain(x0.range().map(function(x) {
return (x - translate[0]) / scale;
}).map(x0.invert));
我们正在用 setInterval
每秒更改 x.domain
,因为我们想要生成背景移动的外观,但是每次运行事件时 d3.behavior.zoom()
(缩放或平移)x.domain
自动切换到初始值 。在下一个链接中,您可以查看问题。
最佳答案
如果您以编程方式更改比例尺的域,则需要将比例尺重新分配给缩放行为。这是因为缩放行为在内部存储了比例的克隆,用于计算新域的新比例和平移偏移。因此,如果您不重新分配比例,它将继续使用(旧的)克隆比例。
我已经更新了 documentation包括关于此的注释。
还有一个额外的复杂性,即缩放的 x 和 y 尺度应该代表缩放比例 = 1 时的域。因此,您实际上需要在 zoom scale=1 处保留当前比例的克隆,并将偏移量应用于克隆和当前比例。
然后,您可能还需要反转当前缩放平移和缩放,具体取决于您需要的确切行为。
所以它看起来应该是这样的:
var x0 = d3.scale.linear().domain(…).range(…), // initial scale
x = x0.copy(); // copy to use for axes and zoom behaviour
setInterval(function() {
var translate = zoom.translate(),
scale = zoom.scale(),
xd = x0.domain(),
dx = 1;
// Set a new x-domain: offset by dx.
x0.domain([xd[0] += dx, xd[1] += dx]);
// Set the zoom x-domain (this resets the domain at zoom scale=1).
zoom.x(x.domain(xd));
// Reset the domain relative to the current zoom offsets.
x.domain(x0.range().map(function(x) {
return (x - translate[0]) / scale;
}).map(x0.invert));
}, 1e3);
Example这在行动中。
关于javascript - 使用 setInterval 设置 x.domain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409955/