I am trying to save a collage of images created on a React Canvas Front end. However since I am fetching my images from a server, it is giving me the following error: Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
My code is as follows:
const imgHidden = new Image();
imgHidden.src = layer
imgHidden.crossOrigin="Anonymous"
imgHidden.onload= () => {
const ctxHidden = hiddenCanvas.current.getContext("2d")
ctxHidden.clearRect(0, 0, hiddenCanvas.width, hiddenCanvas.height);
ctxHidden.drawImage(imgHidden, 0,0, 900, 900)
}
//layer has the url from where image is coming (https://xxx.s3.filebase.com/abc.png)
function saveImage() {
let imageToSave = new Image();
imageToSave.crossOrigin="anonymous"
imageToSave.src = hiddenCanvas.current.toDataURL('image/png', 1.0);
setSavedImage(imageToSave.src)
//alert("Patience Lurker! Minting isn't active yet!")
}
The server where I have stored my images has an option of adding CORS. I added the following JSON:
{
"CORSRules": [
{
"AllowedHeaders": [],
"AllowedMethods": [
"GET"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
}
However it did not work. What "allowed methods" do I need to add for this to work in React Canvas?
Occasionally it gives me this error: Access to image at 'https://bucketname.s3.filebase.com/2.png' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Also, due to the imgHidden.crossOrigin="Anonymous"
line in the draw function, I get an error:
GET https://traits.s3.filebase.com/101.png net::ERR_FAILED 200
while trying to dynamically change images on canvas. So basically my canvas stops working if this line is present and if I remove the line, the CORS issue prevents me from saving the base64.
As it turns out, the problem lies with Filebase server. Despite having the correct CORS config via AWS command line (by uploading a json), the server doesn't apply these to my bucket. To anyone troubleshooting CORS issues I have two tips:
Use this site to figure out if the CORS on your server is setup right: https://cors-test.codehappy.dev/
Use an IMGUR image link in your canvas instead of the image from the server. If IMGUR works (as it did in my React app) it means the CORS config on the server is wrong. If IMGUR link doesn't work it means your react code is wrong.
Remember to add the line img.crossOrigin="anonymous"
BEFORE img.src
.
Hope my 2.5 day ordeal helps others.