问题描述
我正在尝试使用 d3.js 的 d3.behavior.drag()
drag
事件来更新我的数据模型(不立即设置元素位置),然后运行我的绘图"功能以根据更新的模型更新所有元素.此外,我在包含的组元素上使用 translate transform
以移动与拖动对象关联的所有元素(我从下面链接的示例中删除了额外的元素).这会导致拖动的元素在拖动时断断续续,拖动速度越快,情况越糟.
I'm trying to use d3.js's d3.behavior.drag()
drag
event to update my data model (without setting the element position immediately), then run my "draw" function to update all elements based on the updated model. Additionally, I'm using a translate transform
on the containing group element in order to move all the elements associated with the dragged object (I removed the extra elements from the example linked below). This causes the dragged elements to stutter as it's dragged, which gets worse the faster you drag it.
请参阅 有关 jsFiddle 的精简示例.
示例代码如下:
blocks = [
{ x: 0, y: 0 }
];
drag = d3.behavior.drag()
.origin(Object)
.on("drag", function(d) {
d.x = d3.event.x;
d.y = d3.event.y;
draw();
});
svg = d3.select("body")
.append("svg:svg")
.attr("width", 600)
.attr("height", 600);
function draw() {
g = svg.selectAll("g")
.data(blocks);
gEnter = g.enter().append("g");
g.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });
gEnter.append("rect")
.attr("height", 100)
.attr("width", 100)
.call(drag);
}
draw();
推荐答案
您正在 rect
元素上调用 drag
,但您正在转换其父元素:<代码>g 元素.
You are calling drag
on the rect
element, but you're transforming its parent: the g
element.
问题在于拖动组件使用鼠标相对于父级的位置来确定新的d3.event.x
和d3.event.y
.因此,如果您在用户拖动时移动(即 transform
)父对象,事情就会变得一团糟.
The problem is that the drag component uses the mouse location relative to the parent to determine the new d3.event.x
and d3.event.y
. So, if you move (i.e. transform
) the parent while the user drags, things get messed up.
解决方案是在您四处移动的同一元素上调用 drag
;在这种情况下 g
元素:
The solution is to call drag
on the same element that you are moving around; in this case the g
element:
function draw() {
g = svg.selectAll("g")
.data(blocks);
gEnter = g.enter().append("g")
.call(drag);
g.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });
gEnter.append("rect")
.attr("height", 100)
.attr("width", 100);
}
见更正的小提琴:http://jsfiddle.net/EMNGq/14/
这篇关于“口吃"使用 d3.behavior.drag() 和转换时拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2