1

I have an element with an id which I need to select, then drag and drop into a drawing canvas. How do I do this?

The element is outside the canvas and I need to draw it inside the canvas.

function createEvent(typeOfEvent) {
    var event = document.createEvent("CustomEvent");
    event.initCustomEvent(typeOfEvent, true, true, null);
    event.dataTransfer = {
        data: {},
        setData: function (key, value) {
            this.data[key] = value;
        },
        getData: function (key) {
            return this.data[key];
        }
    };
    return event;
}
function dispatchEvent(element, event, transferData) {
    if (transferData !== undefined) {
        event.dataTransfer = transferData;
    }
    if (element.dispatchEvent) {
        element.dispatchEvent(event);
    } else if (element.fireEvent) {
        element.fireEvent("on" + event.type, event);
    }
}
function simulateHTML5DragAndDrop(element, target) {
    var dragStartEvent = createEvent('dragstart');
    dispatchEvent(element, dragStartEvent);
    var dropEvent = createEvent('drop');
    dispatchEvent(target, dropEvent, dragStartEvent.dataTransfer);
    var dragEndEvent = createEvent('dragend');
    dispatchEvent(element, dragEndEvent, dropEvent.dataTransfer);
}
1

You can try using Actions for drag and drop actions.

Actions dragdrop = new Actions(driver);
WebElement object1 = driver.findElement(By.xpath("XPATH1"));
WebElement canvas = driver.findElement(By.xpath("XPATH2"));
dragdrop.moveToElement(object1).clickandHold();
dragdrop.moveToElement(canvas);
dragdrop.release();
dragdrop.build().perform();

You can also use the following code if the above one does not work.

Actions dragdrop = new Actions(driver);
WebElement object1 = driver.findElement(By.xpath("XPATH1"));
WebElement canvas = driver.findElement(By.xpath("XPATH2"));
dragdrop.dragAndDrop(object1, canvas);
dragdrop.build().perform();

There is another type of dragandDrop(source, x-offset, y-offset) action which accepts offsets arguments. You may also try using it if these solutions does not work.

  • It's not working for me . Actually scenerio is ,I will drag the element to inside the canvas . Element which I am dragging is not a canvas. When I drop it in canvas , itself create image or drawing . – sathish kumar May 18 '18 at 3:48
  • This too not working, can you help me to work with offset..I think offset will work – sathish kumar May 18 '18 at 7:46
  • Maybe this question will help in getting the offsets - stackoverflow.com/questions/21461347/… – Rishikesh May 18 '18 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.