我们打开谷歌访问的时候,发现谷歌图片加载之前会先预加载出来图片的主题颜色,当时就觉得很有意思,效果是这样
当然他们这个是后端给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> <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>
剩下的,效果一出,大家一目了然,就是这么简单。
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com