Recently when I use Html5 canvas to capture video screenshots and save the screenshots to an image, it through the error Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported. This article will tell you how to fix it.
1. How To Fix The Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.
- Below is the detailed exception error message.
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at captureVideo (file:///Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/html/canvas/video/html5-canvas-capture-video-webpage-screenshots.js:52:43) at HTMLInputElement.onclick (file:///Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/html/canvas/video/html5-canvas-capture-video-webpage-screenshots.html:21:86) captureVideo @ html5-canvas-capture-video-webpage-screenshots.js:52 onclick @ html5-canvas-capture-video-webpage-screenshots.html:21
- Below is the javascript source code that will through the exception.
// get the html video element. var video = document.getElementById(videoId); // draw the video current screenshot to an image. canvasCtx.drawImage(video, 0, 0, canvas.width, canvas.height) // get the image binary string. const imgBase64String = canvas.toDataURL("image/png");
- The error happened in the code line const imgBase64String = canvas.toDataURL(“image/png”);.
- Finally, I find a way to fix this issue.
- I should create a local web server for example apache tomcat, and IIS.
- I just run the python built-in web server by executing the command python -m http.server in a terminal.
$ python -m http.server Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
- And then copy the Html file and JS file to the webserver, and browse the Html file with the HTTP URL such as http://localhost:8000/html/canvas/video/html5-canvas-capture-video-webpage-screenshots.html
- And now the error is fixed.