6

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

不幸的是,我无法让代码正常工作。我希望主色是名为 .div 的 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

4 回答 4

9

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

感谢@Shadow Wizard 和@ejegg

请参阅要求 jQuery 在执行某些操作之前等待所有图像加载的官方方式

编辑:好的,使用这个有效的小提琴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>

于 2013-09-03T20:50:13.030 回答
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);
于 2013-09-03T20:30:11.343 回答
6

我挣扎了几个小时才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];
于 2013-10-07T21:37:50.837 回答
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;

希望它可以帮助任何人

于 2016-08-13T00:06:16.867 回答