我希望我的 d3 能够在平移时滚动整个页面。
有点像effect on challonge ,但仅在 y 轴上。
这是我的尝试。
pan.call(d3.drag().on("drag", function dragged() {
// x axis
thisPosX += d3.event.dx;
g.attr("transform", "translate(" + thisPosX + ", 0)");
g1.attr("transform", "translate(" + thisPosX + ", 0)");
position.x = thisPosX;
// y axis.
var tmp = d3.event.dy;
if (tmp != -lastTmp) {
$window.scrollTo(0, $window.scrollY - tmp);
lastTmp = tmp;
}
}));
但是这段代码仍然使平移非常滞后并且有一些尖峰。
有更好的方法吗?顺便说一句,我正在使用 Angular。
最佳答案
我认为你想做的事情不需要 d3。当然,您可以使用 d3 绑定(bind)事件,但拖动行为旨在将元素拖动到静态的容器(例如 canvas 或 svg)内。
我找到了这个Codepen这可能会完成工作。
首先,我建议你将 svg 包装在一个具有拖动行为的 div 中,如果你查看它的源代码,Challonge 就会这样做:
然后定义拖动行为的滚动,我已经调整了之前的codepen以使用d3:
var curYPos = 0;
var curDown = false;
var scrollable = d3.select('#scrollable');
scrollable.on('mousemove', function () {
// Scroll only if mouse is down
if (curDown === true){
// Scroll only along Y
// d3.mouse(this) is the position of the cursor inside your scrollable (this)
window.scrollTo(0, document.body.scrollTop + (curYPos - d3.mouse(this)[1]));
}
});
scrollable.on('mousedown', function () {
curDown = true;
curYPos = d3.mouse(this)[1];
});
scrollable.on('mouseup mouseleave', function () {
curDown = false;
});
关于javascript - 如何使用d3滚动整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966660/