Java – Elements do not move within the Canvas

Elements do not move within the Canvas… here is a solution to the problem.

Elements do not move within the Canvas

I would love to move elements around in Canvas, but somehow it doesn’t happen.

Code I tried:

        Actions actions = new Actions(driver);
        actions.moveToElement(flowCanvas, 434, 177);
        actions.clickAndHold();
        actions.moveToElement(flowCanvas, 592 , 373);
        actions.release();
        actions.perform();

My XPath :

   @FindBy(xpath = "//div[@id='diagramDiv']//canvas")
    protected WebElement flowCanvas;

URL I’m trying: https://gojs.net/latest/samples/panelLayout.html

I’m using selenium webdriver and Java. I didn’t get any error in the code above, but it doesn’t move the element either.

Try moving the following elements:

enter image description here

Solution

Basically, the problem is the coordinates you use and the bowser/web driver implementation you’re using. W3C specification states that the Action command offset starts from the center of the element. But not all network driver implementations follow this. So basically the x and y offsets of the moveToElement gecko driver (Firefox) are calculated from the center of the element in your case from the center of the canvas, but for the Chrome driver (Google Chrome), the coordinates are calculated from the top left corner. So, if you want cross-browser support for drag and drop, you will need something like this.

WebDriver driver = getDriver();

driver.get("https://gojs.net/latest/samples/panelLayout.html");
WebElement flowCanvas = driver.findElement(By.xpath("//div[@id='myDiagramDiv']//canvas"));

if(isGoogleChrome()){
    new Actions(driver)
   .moveToElement(flowCanvas, 100, 125).clickAndHold()
   .moveToElement(flowCanvas, 150, 175).release()
   .perform();
} else if (isFireFox()){
    new Actions(driver)
    .moveToElement(flowCanvas, -50, -50).clickAndHold()
    .moveToElement(flowCanvas, 100, 100).release()
    .perform();
}

As you can see, for Firefox you have to move the mouse from the center to the upper-left element in the Canvas with a negative value, and for Chrome you need to move the mouse down and to the right a little.

Related Problems and Solutions