简体   繁体   中英

Unable to get image data from canvas because the canvas has been tainted by cross-origin data

I am using html5 Canvas to get colors from image. For this i wrote the following code in javascript :

http://jsfiddle.net/8dQSS/1/ (Pls check the console to see the exception)

function getImageColor() {
    var colors = [];
    var image = new Image();

    image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        // Draw the image in canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0);

        // Get the pixel data
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        // Loop through imageData.data - an array with 4 values per pixel: red, green, blue, and alpha
        for (var x = 0; x < imageData.width; x++) {
            for (var y = 0; y < imageData.height; y++) {
                var index = 4 * (y * imageData.width + x);
                var r = imageData.data[index];
                var g = imageData.data[index + 1];
                var b = imageData.data[index + 2];
                var a = imageData.data[index + 3];

                colors.push("rgb(" + r + "," + g + "," + b + ")");
            }
        }
    };
    image.src = "http://www.xxxxxxxxxxxx.com/demos/assets/image.jpg";
}

The above code is throwing the following exception :

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
Uncaught Error: SECURITY_ERR: DOM Exception 18 

Can anybody please tell me how to solve this issue?

Are you using this through file system .? If yes then run it on the server(localhost).

The only solution I know is to have the image you want to load hosted on the same server as your files, you can't access and handle any image you want on the web through your canvas.

EDIT : If you want you can do like this .

I got this same error. I searched a lot about crossorigin on canvas. The first solution was add the img.crossOrigin='anonymous' . But the problem still remains. I was using assets served by s3, and fixed the problem adding this on the bucket policy.

{
  "Version": "2008-10-17",
  "Statement": [
     {
       "Sid": "AllowPublicRead",
       "Effect": "Allow",
       "Principal": {
         "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::seu-candidato/*"
     }
  ]
}

The assets from bucket had some params like X-Amz-Expires , X-Amz-Date I removed them and my problem ws fixed

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