When using d3, how to trigger drag with only mouse events?

血红的双手。 提交于 2021-01-29 07:20:43

问题


There are some discussions around triggering d3 drag programmably. Usually people give a work around way. Like store the drag function and trigger it directly. So is there a way to trigger d3 drag using mouse events? The d3 drag must be implemented according to mouse events. In my app, there are complicated drag setups and expose the drag handlers is not feasible. Also, I hope the code is tested only on boundaries instead of having to open it up.

I'm wondering how d3 implemented the drag. I have tried to dispatch mousedown and mousemove events, but it doesn't work. Here is my testing code.

    const circles = document.querySelectorAll('.edit-handler');
    const clientRect = circles[0].getBoundingClientRect();
    const clientX = (clientRect.left + clientRect.right) / 2;
    const clientY = (clientRect.top + clientRect.bottom) / 2;
    circles[0].dispatchEvent(
        new MouseEvent('mousedown', {clientX, clientY, buttons: 1}));
    circles[0].dispatchEvent(
        new MouseEvent('mousemove', {clientX, clientY, buttons: 1}));
    circles[0].dispatchEvent(new MouseEvent(
        'mousemove',
        {clientX: clientX + 100, clientY: clientY + 100, buttons: 1}));

回答1:


Ok, I figured it out

Looks like the view: window is the deal breaker. I don't quite understand the importance but it works. If you know why, please make comments to let me and others know.

    const circles = document.querySelectorAll('.edit-handler');
    const clientRect = circles[0].getBoundingClientRect();
    const clientX = (clientRect.left + clientRect.right) / 2;
    const clientY = (clientRect.top + clientRect.bottom) / 2;
    circles[0].dispatchEvent(new MouseEvent('mousedown', {
      clientX,
      clientY,
      view: window, // After adding this, it works.
    }));
    circles[0].dispatchEvent(new MouseEvent('mousemove', {
      clientX,
      clientY,
    }));
    circles[0].dispatchEvent(new MouseEvent('mousemove', {
      clientX: clientX + 100,
      clientY: clientY + 100,
    }));
    circles[0].dispatchEvent(new MouseEvent('mouseup', {
      clientX: clientX + 100,
      clientY: clientY + 100,
      view: window, // Here too
    }));


来源:https://stackoverflow.com/questions/64289838/when-using-d3-how-to-trigger-drag-with-only-mouse-events

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