When drawing an external link image in canvas, we will encounter a cross-domain problem.
Examples are 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 <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 opening this page in a 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 images can be used, drawing 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() cannot be used. toDataURL(), or getImageData() method; the above security error will be thrown when using these methods
This is a troublesome problem, but fortunately img has added the crossorigin attribute, which 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 <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, a perfect solution!
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.