简体   繁体   中英

How to solve “ The canvas has been tainted by cross-origin data.” when I try to use getImageData

I have tried to implement a invert color function to my function, but I don't how to solve this thing with Cross Origin.

I have tried to use the "Anonymous", but that does not work too. So the question is pretty simple. How to use this getImageData correctly?

    var canvasOriginal = document.getElementById("imagemOriginal");
    var ctxOriginal = canvasOriginal.getContext("2d");

    var imgOriginal = new Image();
    var imgOut = new Image();

    imgOriginal.src = 'images-png/img1.png';

    imgOriginal.onload = function (){

        ctxOriginal.drawImage(imgOriginal,0,0,512,512);

        imgOut = ctxOriginal.getImageData(0,0,512,512);

        for (let i = 0; i < imgOut.data.length; i += 4) {
            imgOut.data[i] = 255 - imgOut.data[i];
            imgOut.data[i+1] = 255 - imgOut.data[i+1];
            imgOut.data[i+2] = 255- imgOut.data[i+2] ;
        }
        ctxOriginal.putImageData(imgOut, 512, 0);       
    };

Yes, I created a localhost and it has worked, but I had to add an extension on Google Chrome called "Allow-Control-Allow-Origin" to work. Thanks!

I think that the error is because your browser knows itself as localhost (or server you are on) and the canvas thinks your image is not coming from localhost or that server. If you're uploading locally your image should be something like

<img src="blob:http://your-server-address-or-localhost/image-id-returned-from-upload">

or if the image already exists, it would be something similar:

<img src="http://your-server-address-or-localhost/images-png/img1.png">

I imagine what you have is something like this:

<img src="/images-png/img1.png">

and that trips up the canvas

Your imgOriginal.src should be:

imgOriginal.src = 'http://localhost:3000/images-png/img1.png';

Hope this helps.

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