1

我正在尝试使用 selenium 捕获一个画布部分屏幕截图。我已使用元素的位置来捕获屏幕截图,如下所示。不幸的是,我没有按预期获得剖面图。我可以观察到实际图像和预期图像的更多差异。在下面的屏幕截图中,绿色框表示预期的图像,红色框表示实际的图像。

在此处输入代码

我尝试过以下两种方法,但结果都是一样的。

方法一:

public void captureSectionScreenshot(WebDriver driver){

    try{
        WebElement canvasElement = driver.findElement(By.tagName("canvas"));
        System.out.println("Map X"+canvasElement.getLocation().getX());
        System.out.println("Map Y"+canvasElement.getLocation().getY());

        // Get entire page screenshot
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        BufferedImage fullImg = ImageIO.read(screenshot);
        // Get the location of element on the page
        Point point = canvasElement.getLocation();
        // Get width and height of the element
        int eleWidth = canvasElement.getSize().getWidth();
        int eleHeight = canvasElement.getSize().getHeight();

        BufferedImage eleScreenshot= fullImg.getSubimage( point.getX(), point.getY(),
                eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);
        // Copy the Section screenshot to disk
        File screenshotLocation = new File("***********************************\\CanvasScreenshot.png");
        FileUtils.copyFile(screenshot, screenshotLocation);

    }catch(Exception e){
        System.out.println("Error is Occured :"+e.getStackTrace());
    }
}

方法2:(使用Ashot)

public void captureScreenshot(WebDriver driver){

    String actualOutputImagePath="**************************\AShot_CanvasScreenshot.png";
    WebElement canvasElement = driver.findElement(By.tagName("canvas"));
    Screenshot screenshot = new AShot().coordsProvider(
            new WebDriverCoordsProvider()).takeScreenshot(driver,canvasElement);
    BufferedImage actualImage = screenshot.getImage();

    try{
        ImageIO.write(actualImage, "png", new File(actualOutputImagePath));

    }catch (Exception e){
        System.out.println(e.getStackTrace());
    }
}

HTML:

<div id="map" class="map">
    <div class="ol-viewport" data-view="3" style="position: relative; overflow: hidden; width: 100%; height: 100%; touch-action: none;">
        <canvas class="ol-unselectable" width="268" height="500" style="width: 100%; height: 100%; display: block;"></canvas>
        <div class="ol-overlaycontainer"></div>
        <div class="ol-overlaycontainer-stopevent">
        </div>
    </div>
</div>
4

0 回答 0