“口吃”拖动时使用d3.behavior.drag()和transform [英] "Stuttering" drag when using d3.behavior.drag() and transform

查看:145
本文介绍了“口吃”拖动时使用d3.behavior.drag()和transform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用d3.js的 d3.behavior.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()​;


推荐答案

/ code>在 rect 元素,但是你正在转换其父: 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()和transform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆