Lately I’ve been doing some work on an HTML file I have on my desktop, to play around with Canvas. Unfortunately, using images stored on your local machine causes some issues with Canvas. Specifically, I’ve been getting errors saying “Tainted canvases may not be exported.”. The “tainted canvas” is a result of drawing an image that violates CORS policies. To get around this issue, I have been using the data URL of the image as the image source.
What is a data url? It’s a url that represents a file’s data, with a specification of the file type. If the file is an image, navigating to the data url in Chrome specifically will result in the image being displayed. Typically, with <img> tags, you specify a hosted image url as the source. Similarly, setting the “src” attribute of <img> tags to the data url of the image displays the image.
How to get a data url
The easiest way to get a data url from an image is to load the image using a FileReader and checking the Result property. A demo is below to show how to leverage a FileReader and Canvas to get the data url of a selected image. It uses an input, and on change it updates the text box to be the data url and draws the result onto the canvas.
As noted in the stack overflow link, there are certainly other ways to get around the Tainted Canvas error. However, leveraging the data url worked for me, mostly because I was calling canvas .toDataUrl() elsewhere in my code.