Selenium を使用して 1 つのキャンバス セクションのスクリーンショットをキャプチャしようとしています。要素の場所を使用して、以下のようにスクリーンショットをキャプチャしました。残念ながら、セクション イメージが期待どおりに得られません。実際の画像と予想される画像の違いを観察できます。以下のスクリーンショットでは、緑色のボックスが予想されるものを示し、赤色のボックスが実際の画像を示しています。
以下の2つのアプローチで試しましたが、どちらも同じ結果になります。
アプローチ 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>