简体   繁体   中英

Exporting image data from an HTML canvas results in “Tainted Canvas” error or white image

The following code crops a portion of an image. I'd like to get the image data for the cropped area in base64, and I tried to do it using context.toDataURL() :

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var imageObj = new Image(); //imageObj.crossOrigin = "anonymous"; imageObj.onload = function () { // crop from 0,0, to 250,150 var cropX = 0; var cropY = 0; var cropWidth = 250; var cropHeight = 150; //resize our canvas to match the size of the cropped area canvas.style.width = cropWidth; canvas.style.height = cropHeight; //fill canvas with cropped image context.drawImage( imageObj, cropX, cropY, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height ); } imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; setTimeout(() => { var dataURL = canvas.toDataURL(); console.log(dataURL); $("#my_image").attr("scr", dataURL); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <head> </head> <body> <canvas id="myCanvas"></canvas> <img id="my_image" src="" style="border:1px solid red;"> </body> </html>

However, it either shows a blank image or I get this error:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

What am I doing wrong?

You're attempting to save an image that's been fetched from an external source. CORS does not allow this unless the site the image has been fetched from explicitly has you whitelisted:

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

If you need to save image information, use an image that you have local access to (eg from your assets folder or a file upload).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM