我的树形图上有一个缩放事件处理程序,如下所示:
d3.select("#"+canvasId+" svg")
.call(d3.behavior.zoom()
.scaleExtent([0.05, 5])
.on("zoom", zoom));
它调用处理平移边界逻辑的缩放函数:
function zoom() {
console.log(d3.event.translate[0]);
var wcanvas = $("#"+canvasId+" svg").width();
var hcanvas = $("#"+canvasId+" svg").height();
var displayedWidth = w*scale;
var scale = d3.event.scale;
var h = d3.select("#"+canvasId+" svg g").node().getBBox().height*scale;
var w = d3.select("#"+canvasId+" svg g").node().getBBox().width*scale;
var padding = 100;
var translation = d3.event.translate;
var tbound = -(h-hcanvas)-padding;
var bbound = padding;
var lbound = -(w-wcanvas)-padding;
var rbound = padding;
// limit translation to thresholds
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)
];
console.log("Width: "+w*scale+" || Height: "+h*scale+" /// "+"Left: "+translation[0]+" || Top: "+translation[1]);
d3.select("#"+canvasId+" svg g")
.attr("transform", "translate(" + translation + ")" +" scale(" + scale + ")");
console.log(d3.select("#"+canvasId+" svg g")[0]);
}
但是,超出范围的翻译会导致 d3.event.translate 值增加。结果是,即使平移没有导致图形移动,因为它已达到平移限制,连续事件中的平移值也会继续增加。
结果是,假设我将图表向左拖动很远,即使它会停止移动超过某个点,因为事件中的值继续增加,所以我必须将它向右拖动很远在它真正开始再次向右移动之前。
有什么好的方法可以防止这种行为吗?
最佳答案
好的,我已经解决了。诀窍是设置 d3.behaviour.zoom 的平移,以便连续的缩放平移从有界平移开始,而不是从实际上不产生任何移动的附加平移开始。
为此,我们将缩放行为声明为单独的变量并将其添加到可缩放元素中:
var zoomBehaviour = d3.behavior.zoom()
.scaleExtent([0.05, 5])
.on("zoom", zoom)
d3.select("#"+canvasId+" svg")
.call(zoomBehaviour);
然后我们将此 ZoomBehaviour 的平移设置为缩放函数中的有界平移:
function zoom() {
...
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)
];
zoomBehaviour.translate(translation);
d3.select("#"+canvasId+" svg g")
.attr("transform", "translate(" + translation + ")" +" scale(" + scale + ")");
}
关于javascript - 防止缩放事件中的 d3 平移值超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981519/