无法从画布获取图像数据,因为画布已被跨源数据污染 [英] Unable to get image data from canvas because the canvas has been tainted by cross-origin data

查看:489
本文介绍了无法从画布获取图像数据,因为画布已被跨源数据污染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用html5 Canvas从图像中获取颜色.为此,我在javascript中编写了以下代码:

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

http://jsfiddle.net/8dQSS/1/(请检查控制台以查看异常)

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?

推荐答案

我知道的唯一解决方案是将要加载的图像与文件托管在同一服务器上,您将无法访问和处理任何图像想要通过您的画布上网.

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.

如果需要,您可以 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆