1. 程式人生 > >獲取圖片主體背景色

獲取圖片主體背景色

我們開啟谷歌訪問的時候,發現谷歌圖片載入之前會先預加載出來圖片的主題顏色,當時就覺得很有意思,效果是這樣圖片描述

當然他們這個是後端給json的時候給了個顏色程式碼,暫且不提,但如果前端來做的話,也是有方法的,張鑫旭大神的部落格裡就記載的有,是一個叫rgbaster.js的玩意兒,具體用法我先給貼下來了。rgbaster.js的內容是:

!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):n.RGBaster=t()}(this,function(){"use strict";var t=function(n,o){var u=new Image,t=n.src||n;"data:"!==t.substring(0,5)&&(u.crossOrigin="Anonymous"),u.onload=function(){var n,t,e,r=(n=u.width,t=u.height,(e=document.createElement("canvas")).setAttribute("width",n),e.setAttribute("height",t),e.getContext("2d"));r.drawImage(u,0,0);var i=r.getImageData(0,0,u.width,u.height);o&&o(i.data)},u.src=t},s=function(n){return["rgb(",n,")"].join("")},f=function(n,t){return{name:s(n),count:t}},n={};return n.colors=function(n,u){var a=(u=u||{}).exclude||[],c=u.paletteSize||10;t(n,function(n){for(var t={},e="",r=[],i=0;i<n.length;i+=4)r[0]=n[i],r[1]=n[i+1],r[2]=n[i+2],e=r.join(","),-1===r.indexOf(void 0)&&0!==n[i+3]&&-1===a.indexOf(s(e))&&(t[e]=e in t?t[e]+1:1);if(u.success){var o=function(n,t){if(n.length>t)return n.slice(0,t);for(var e=n.length-1;e<t-1;e++)n.push(f("0,0,0",0));return n}(function(n){var t=[];for(var e in n)t.push(f(e,n[e]));return t.sort(function(n,t){return t.count-n.count}),t}(t),c+1);u.success({dominant:o[0].name,secondary:o[1].name,palette:o.map(function(n){return n.name}).slice(1)})}})},n});

具體html和js的使用程式碼是:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>獲取圖片主題色指令碼擴充套件的完整的示例</title>
    <script src="./rgbaster.js"></script>
</head>

<body>
    <div id="box" style="width:500px;height: 500px;">
        <img src="mm4.jpg" alt="" id="image">
    </div>
    <script type="text/javascript">
    var img = document.getElementById('image');
    var box=document.getElementById('box');
    RGBaster.colors(img, {
        // return up to 30 top colors from the palette  從調色盤返回最多30個頂級顏色
        paletteSize: 30,
        // don't count white
        //排除 白色
        exclude: ['rgb(255,255,255)'],
        // do something when done
        //獲取成功之後
        success: function(payload) {
            box.style.background=payload.dominant;
            console.log('Dominant color:', payload.dominant);
            console.log('Secondary color:', payload.secondary);
            console.log('Palette:', payload.palette);
        }
    })
    </script>
</body>
</html>

剩下的,效果一出,大家一目瞭然,就是這麼簡單。