我們打開(kāi)谷歌訪問(wèn)的時(shí)候,發(fā)現(xiàn)谷歌圖片加載之前會(huì)先預(yù)加載出來(lái)圖片的主題顏色,當(dāng)時(shí)就覺(jué)得很有意思,效果是這樣
當(dāng)然他們這個(gè)是后端給json的時(shí)候給了個(gè)顏色代碼,暫且不提,但如果前端來(lái)做的話,也是有方法的,張?chǎng)涡翊笊竦牟┛屠锞陀涊d的有,是一個(gè)叫rgbaster.js的玩意兒,具體用法我先給貼下來(lái)了。
rgbaster.js的內(nèi)容是:
!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> <head> <meta charset="UTF-8"> <title>獲取圖片主題色腳本擴(kuò)展的完整的示例</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 從調(diào)色板返回最多30個(gè)頂級(jí)顏色 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>
剩下的,效果一出,大家一目了然,就是這么簡(jiǎn)單。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com