The purpose is to be able to perform painting operations on the HTML5 canvas element.
Specific examples:
package cn.om.TestHTML5; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; public class TestHTML5Canvas { WebDriver driver; String url; @Test public void testHTML5Canvas() throws Exception { File captureScreenFile = null; driver.get(url); JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; // The video object is placed in the iframe, you must switch to the iframe first to locate the video element WebElement iframe = driver.findElement(By.xpath(".//*[@id='result']/iframe")); driver.switchTo().frame(iframe); /* * Call the JavaScript statement to draw a red rectangle on the canvas element getElementById('myCanvas') statement to get the canvas element on the page * var cxt=c.getContext('2d') set the canvas to 2d cxt.fillStyle='#FF0000' set the fill color to red * cxt.fillRect(0,0,150,150); draw a rectangle on the canvas */ jsExecutor.executeScript("var c=document.getElementById('myCanvas');" + "var cxt=c.getContext('2d');" + "cxt.fillStyle='#FF0000';" + "cxt.fillRect(0,0,150,150);"); captureScreenFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(captureScreenFile, new File("F:\\workspace\\WebDriver API\\2017-2-23\\canvas.jpg")); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(); url = "http://www.w3school.com.cn/tiy/t.asp?f=html5_canvas_line"; } @AfterMethod public void afterMethod() { driver.quit(); } }