Html5 canvas Automated Testing
The automated test of canvas is not very easy, because, to put it bluntly, it is an image. I don't know what I drew on the canvas.
The only method that comes to mind is comparison.
The specific method is also very simple.
First, write the case and run it. First, manually confirm whether it is correct. If it is correct, OK. Cut down the canvas image and use it as an expected chart. Then, compare the case with the expected chart directly.
The comparison between the graph and graph requires the support of some libraries.
I have used resemble and the code is on github.
This is also very simple.
Code on
function compare(){ var str = canvasElement.toDataURL('image/png'); resemble(str) .compareTo('xxx.jpg') .onComplete(function (data) { console.log(data.isSameDimensions + " " + data.misMatchPercentage); }); }
You can use toDataURL to convert the canvas content into an image and then compare it with the expected image.
The output result is
IsSameDimensions indicates whether the two images are the same size,
MisMatchPercentage indicates the percentage difference between the two graphs.
With this, you can happily assert.
Let's talk about how to generate this expectation chart.
It is also very simple
function savepic() { var str = canvasElement.toDataURL('image/png'); var link = document.createElement("a"); link.download = "abc"; link.href = str; link.click(); }
Use toDataURL, create a link, and call click to download the link.
By the way, Baidu hasn't been using this simple method for a long time, but google has come out. I don't know if my keyword is incorrect, or because I am too white.