目的是能够在HTML5的画布元素上进行绘画操作。
具体实例:
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;
// video对象放在iframe里,要先切换到iframe中,才能定位到video元素
WebElement iframe = driver.findElement(By.xpath(".//*[@id='result']/iframe"));
driver.switchTo().frame(iframe);
/*
* 调用JavaScript语句,在画布元素上画一个红色矩形的团 getElementById('myCanvas')语句获取页面上的画布元素
* var cxt=c.getContext('2d')设定画布为2d cxt.fillStyle='#FF0000'设定填充色为红色
* cxt.fillRect(0,0,150,150);画布上绘制矩形
*/
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();
}
}