Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - Color Thief won’t work …

I’d like to use Color Thief, a script which allows you to extract the dominant color of an image.

Unfortunately I’m not able to get the code to work. I’d like the dominant color to be the background color of a div called mydiv.

Here’s what I have so far: http://jsfiddle.net/srd5y/4/

Updated code / transfered to my own server due to cross-linking issues: 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>

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this based on your code and a mix of everyone's answers. You need to wait for the image to load before using Color Theif. The color for photo1.jpg should be [125, 190, 193]

Thanks @Shadow Wizard and @ejegg

See Official way to ask jQuery wait for all images to load before executing something

EDIT: Ok use this fiddle which works 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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...