Trying to get colors from image

问题: I am trying to use Vibrant.js to get colors from a image, I added vibrant.min.js to my files and tried to use it like: var img = new Image(); img.src = "http://f1.bcbits....

问题:

I am trying to use Vibrant.js to get colors from a image, I added vibrant.min.js to my files and tried to use it like:

var img = new Image();
img.src = "http://f1.bcbits.com/img/a1312167393_16.jpg";

img.addEventListener('load', function() {
    var vibrant = new Vibrant(img);
    var swatches = vibrant.swatches()
    for (var swatch in swatches)
        if (swatches.hasOwnProperty(swatch) && swatches[swatch])
            console.log(swatch, swatches[swatch].getHex())
});

However this gives me the following error:

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
    at t.getImageData (file:///C:/Users/liweda/Downloads/test/js/vibrant.min.js:1:11198)
    at new i (file:///C:/Users/liweda/Downloads/test/js/vibrant.min.js:1:6082)
    at Image.<anonymous> (file:///C:/Users/liweda/Downloads/test/js/functions.js:11:19)

How could I fix this error or are there any alternative options? I need a dominant color and less brighter color


回答1:

The problem is that you're loading an image asset from a 3rd party domain in relation to the domain the javascript code is running from.

For example, if you are running this locally at http://localhost:8080 but its loading the image resource from http://f1.bcbits.com, then the canvas is considered tainted and you can no longer get or manipulate image data from it.

This is a security practice found in all browsers.

If your production website is http://f1.bcbits.com, then the code will work fine. But in order for you to develop this locally, the image you're working with needs to be loaded from the same domain as you're developing in, like localhost.

Edit:

Sorry, I forgot to mention the way to fix this both locally and in production. If you enable the correct CORS headers, the 3rd party domain issue goes away. Take a look at https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

  • 发表于 2018-07-13 23:40
  • 阅读 ( 384 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除