彩色小偷不会工作......

时间:2013-09-03 20:09:38

标签: javascript

我想使用Color Thief,这是一个允许您提取图像主色的脚本。

不幸的是我无法让代码工作。我希望主色作为div mydiv的背景颜色。

以下是我到目前为止的内容:http://jsfiddle.net/srd5y/4/

由于交叉链接问题更新了代码/转移到我自己的服务器:http://moargh.de/daten/color-thief-master/test.html

JS

var sourceImage = 'https://www.google.de/intl/de_ALL/images/logos/images_logo_lg.gif';
var colorThief = new ColorThief();
colorThief.getColor(sourceImage);

HTML

<div id="mydiv"></div>

感谢您的帮助!

4 个答案:

答案 0 :(得分:8)

Murtnowski说,如果针对托管在不同域上的图像运行操作,操作将失败。如果您在自己域上托管的图像上运行它,则只需使用img元素而不是URL调用getColor:

HTML

<img src="/images/foo.jpg" id="myImg" />

JS

var sourceImage = document.getElementById("myImg");
var colorThief = new ColorThief();
colorThief.getColor(sourceImage);

答案 1 :(得分:8)

根据您的代码和每个人的答案混合尝试。在使用Color Theif之前,您需要等待图像加载。 photo1.jpg的颜色应为[125,190,193]

谢谢@Shadow Wizard和@ejegg

请参阅Official way to ask jQuery wait for all images to load before executing something

编辑:好的,请使用这个有效http://jsfiddle.net/bgYkT/

的小提琴

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">


    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="js/color-thief.js"></script>


    <style type="text/css">
        #mydiv {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
        }
    </style>

</head>


<body>

    <img src="img/photo1.jpg" id="myimg" />

    <div id="mydiv"></div>


    <script>
      $(window).ready(function(){
        var sourceImage = document.getElementById("myimg");
        var colorThief = new ColorThief();
        var color = colorThief.getColor(sourceImage);
        document.getElementById("mydiv").style.backgroundColor = "rgb(" + color + ")";
       });
    </script>

</body>

答案 2 :(得分:4)

我挣扎了几个小时让color-thief工作。 最后,[0]的微小添加指向第一个数组元素:

<img id="theimage" src="images/p1-340-thumb.jpg" />

myImage = $('#theimage');
colorThief = new ColorThief();
color = colorThief.getColor(myImage[0]);
red = color[0];
green = color[1];
blue = color[2];

答案 3 :(得分:3)

我遇到了同样的问题,并以这种方式解决了这个问题:

// get my image url
var imageUrl = '//myimage.ulr.com';
// than create an image elm, the sizes are needed. 360x360 on this case
var image = new Image(360, 360);


image.onload = function(){
    // act only after image load
    console.log(image);

    // than colorThief and get the color value 
    var colorThief = new ColorThief();          
    var color = colorThief.getColor(image);
    console.log(color);
};
image.src = imageUrl;

希望它可以帮助任何人