D3 drag event behaviour: DragEvent.x and DragEvent.y values source

你。 提交于 2020-02-24 12:01:35

问题


I don't understand the behaviour of the D3 DragEvent object in Mike Bostock’s examples for D3.

Those are the two examples I don't understand: Circle Dragging I Drag + Zoom

This is the code that I don't understand:

function dragged(d) { d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y); }

In this example, d.x and d.y are part of a data object that contains the last centre of the circle.

What I expect to happen with this code, is that the attributes cx and cy of the circle change to the current value of d3.event.x and d3.event.y

In my view, that should be the coordinates where the mouse is when the user start dragging. If the user is not starting to drag exactly in the centre of the circle, the behaviour I expect is the circle to jump to the place where the user start dragging and, then, a normal dragging behaviour.

My problem is that the initial jump doesn't happen and I don't know why.

I checked the values of d3.event.x and d3.event.y when the code is running and they are exactly the same values of d.x and d.y, never mind where the user click in the circle. I don't understand why that is the case.

Finally, I changed the name (and only the name) in the object (and whenever was necessary in the code), from d.x and d.y to d.m and d.n and the code started to do what I was expecting.

function dragged(d) { d3.select(this).attr("cx", d.m = d3.event.x).attr("cy", d.n = d3.event.y); }

So, the code works differently when the data object has the properties d.x and d.y that when the data object has the properties d.m and d.n. It seems like the object DragEvent is expecting a data object with concrete proprieties but that sounds weird to me and I can't find it documented.

I was expecting to avoid checking D3 source code if somebody know the answer already.


回答1:


What I though a weird behaviour is the intended behaviour.

All DragEvent objects have a 'subject'. The subject is not the SVG shape that is producing the dragging event, but, if it exist, the datum associated to that SVG.

More information available in: https://github.com/d3/d3-drag#drag_subject

So, yes, if the datum object have the the properties x and y, the value would be assigned to the properties dx and dy of the DragEvent object.

As we can see in the d3 source, in the drag.js file:

  dx = s.x - p[0] || 0;
  dy = s.y - p[1] || 0;


来源:https://stackoverflow.com/questions/42844949/d3-drag-event-behaviour-dragevent-x-and-dragevent-y-values-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!