首先看对比图
上述的三张图分别是鼠标移入某个图片后根据获取的图片的原色动态设置的容器渐变背景
那么想要实现这个效果,我们必须先搞定一件事。鼠标移入某个图片获取当前图片的原色
主角上场:colorThief
colorThief
具体怎么操作呢 :
import colorThief from 'colorthief';
//new的方式创建
const ColorThief = new colorThief();
构建一个获取并执行操作的方法
async function setBgColor(img:object,src:string){
//ColorThief 接收两个参数,一个是图片本身,一个是色值获取的范围
//.getPalette 用来执行该获取像素色值的行为
const colors= await ColorThief.getPalette(img, 3)
console.log(colors)
}
分解获取到的色值执行填充背景
async function setBgColor(img:object,src:string){
let el:any =document.getElementsByClassName('mod_cot')[0]
const colors= await ColorThief.getPalette(img, 3)
const [c1,c2,c3] = colors.map((c:any)=>`rgb(${c[1]},${c[1]},${c[2]})`);
el.style.background=`linear-gradient(${c1} 0%,${c2} 50%,${c3} 100%`
}
为了保证获取的时效性采用异步的方式构建使用效果极佳