我正在尝试使用d3js为圆项目实现拖动和缩放事件处理程序。我已经为这两个事件添加了行为,如下所示
var circle = svg.append("circle")
.attr("fill", "green")
.attr("opacity", 0.6)
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 13)
.call(d3.behavior.drag().on("drag", drag))
.call(d3.behavior.zoom().on("zoom", zoom));
没有缩放对象,拖动工作正常。放大/缩小对象后,拖动不起作用,但包含mousedown的所有事件都被捕获为“缩放”事件。
有关完整来源,请参阅http://jsfiddle.net/xTaDC/
似乎我不理解“d3.behavior”。 https://github.com/mbostock/d3/blob/master/examples/mercator/mercator-zoom-constrained.html仅提供缩放处理程序并处理拖动和缩放。
我在这里做错了什么?
答案 0 :(得分:3)
据我所知,d3的缩放行为已经处理了拖动,所以拖动的东西是多余的。尝试使用zoom的d3.event.translate(这是一个2元素数组,所以如果你只想获得x值,你可以去d3.event.translate [0])来复制你的Drag中的功能你的缩放。
其他提示:为了让自己更轻松,请确保在您尝试拖动的任何内容的父级上应用您的呼叫(缩放)。这样可以防止紧张和不稳定的行为。
来源当然是d3维基。 “此行为会自动创建事件侦听器,以处理容器元素上的缩放和平移手势。支持鼠标和触摸事件。” https://github.com/mbostock/d3/wiki/Zoom-Behavior
答案 1 :(得分:3)
我遇到了类似的问题,并通过覆盖缩放的其他子事件来解决它。
在缩放和拖动事件侦听器后添加以下代码
.on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null);
所以完整的代码看起来像
var circle = svg.append("circle")
.attr("fill", "green")
.attr("opacity", 0.6)
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 13)
.call(d3.behavior.drag().on("drag", drag))
.call(d3.behavior.zoom().on("zoom", zoom))
.on("mousedown.zoom", null)
.on("touchstart.zoom", null)
.on("touchmove.zoom", null)
.on("touchend.zoom", null);
答案 2 :(得分:0)
使用敏感事件区域附加图表(必须是最后一个附加):
var rect = svg.append("svg:rect")
.attr("class", "pane")
.attr("width", w)
.attr("height", h);
AFTER(不包含)在此区域添加事件管理
rect.call(d3.behavior.zoom().x(x).scaleExtent([0.5, 4]).on("zoom", draw));
并且绘制函数是
function draw() {
svg.select("g.x.axis").call(xAxis);
svg.select("g.y.axis").call(yAxis);
svg.select("path.area").attr("d", area);
svg.select("path.line").attr("d", line);
}
请参阅此示例:https://groups.google.com/forum/?fromgroups=#!topic/d3-js/6p7Lbnz-jRQ%5B1-25-false%5D
答案 3 :(得分:0)
在2020年,使用d3.zoom启用缩放和平移:https://observablehq.com/@d3/zoom
如果要在允许拖动圆的同时启用背景平移,请参阅官方示例,其中d3.drag和d3.zoom用于不同的元素:https://observablehq.com/@d3/drag-zoom