我正在尝试使用selenium捕获一个画布部分的屏幕截图。我已经使用元素的位置来捕获屏幕截图,如下所示。不幸的是,我没有得到预期的截面图像。我可以观察到实际图像和预期图像之间的更多差异。在下面的屏幕截图中,绿色框表示预期的一个,红色框表示实际的一个。
我尝试了以下两种方法,但是两者的结果相同。
方法1:
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>