How to fix canvas.toDataURL() SecurityError with JavaScript?

Sometimes, we want to fix canvas.toDataURL() SecurityError with JavaScript.

In this article, we’ll look at how to fix canvas.toDataURL() SecurityError with JavaScript.

How to fix canvas.toDataURL() SecurityError with JavaScript?

To fix canvas.toDataURL() SecurityError with JavaScript, we set the crossOrigin attribute to 'anonymous' with setAttribute.

For instance, we write

const img = new Image();
img.setAttribute("crossOrigin", "anonymous");
img.src = url;

to create an image with Image.

Then we set the crossOrigin attribute to 'anonymous' with

img.setAttribute("crossOrigin", "anonymous");

Then we set the img.src to the url that’s returned by canvas.toDataURL.

This works if we have the correct permission to the images in the canvas.

Conclusion

To fix canvas.toDataURL() SecurityError with JavaScript, we set the crossOrigin attribute to 'anonymous' with setAttribute.