簡體   English   中英

縮放事件覆蓋 d3js 中的拖動行為

[英]Zoom event overrides Drag behavior in d3js

我正在嘗試使用 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 的事件都被捕獲為“zoom”事件。

有關完整源代碼,請參閱http://jsfiddle.net/xTaDC/

似乎我不明白“d3.behavior”。 https://github.com/mbostock/d3/blob/master/examples/mercator/mercator-zoom-constrained.html僅提供縮放處理程序並處理拖動和縮放。

我在這里做錯了什么?

據我所知,d3 的縮放行為已經處理了拖動,所以拖動的東西是多余的。 嘗試使用縮放的 d3.event.translate(這是一個 2 元素數組,因此如果您只想獲取 x 值,您可以使用 d3.event.translate[0])來復制拖動到你的變焦。

附加提示:為了讓自己更輕松,請確保將調用(縮放)應用於您嘗試拖動的任何對象的父級。 這將防止緊張和不穩定的行為。

來源當然是 d3 wiki。 “此行為會自動創建事件偵聽器來處理容器元素上的縮放和平移手勢。鼠標和觸摸事件均受支持。” https://github.com/mbostock/d3/wiki/Zoom-Behavior

我遇到了類似的問題並通過覆蓋縮放的其他子事件來解決它。

在縮放和拖動事件偵聽器之后添加以下代碼

.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);

使用敏感事件區域附加您的圖表(必須是最后一個附加):

var rect = svg.append("svg:rect")
    .attr("class", "pane")
    .attr("width", w)
    .attr("height", h);

之后(不包括)在此區域添加事件管理

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

2020年使用d3.zoom啟用縮放和平移: https ://observablehq.com/@d3/zoom

如果要啟用背景平移,同時允許拖動圓圈,請參閱官方示例,其中 d3.drag 和 d3.zoom 用於不同元素: https ://observablehq.com/@d3/drag-zoom

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM