简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM