Home > Article > Web Front-end > How to solve cross-domain problems encountered when drawing on canvas
This article mainly introduces relevant information that explains in detail the cross-domain problems encountered when drawing canvas. The content is quite good. I will share it with you now and give it as a reference.
When drawing an external link image in canvas, we will encounter a cross-domain problem.
The example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>crossorigin</title> </head> <body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script> </body>
When you open this page in the browser, you will find this problem:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
This is limited by the CORS policy and there will be cross-domain problems, although it can be used Image, but drawing it to the canvas will pollute the canvas. Once a canvas is polluted, the data of the canvas cannot be extracted. For example, the canvas toBlob(), toDataURL(), or getImageData() methods cannot be used; when using these methods, it will The above security error is thrown
This is a distressing problem, but fortunately img has added the crossorigin attribute. This attribute determines whether the CORS function is enabled during the image acquisition process:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>crossorigin</title> </head> <body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.setAttribute('crossorigin', 'anonymous'); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script> </body>
Comparing the above two pieces of JS code, you will find this extra line:
image.setAttribute('crossorigin', 'anonymous');
It’s that simple, Perfect solution!
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About the properties of canvas lines
##How to use canvas to achieve image mosaic
The above is the detailed content of How to solve cross-domain problems encountered when drawing on canvas. For more information, please follow other related articles on the PHP Chinese website!