CSS-跟随图片变化的背景色

CSS-跟随图片变化的背景色

  • 获取图片的主要颜色并用于背景渐变
  • 需要安装依赖 colorthief获取图片的主要颜色. 并丢给背景
  • 注意 getPalette并不是个异步方法
    在这里插入图片描述
import styles from './styles.less';
import React, { useState } from 'react';
import Colortheif from 'colorthief';

const colortheif = new Colortheif();
export default function Index() {
  const [activeIndex, setActiveIndex] = useState(-1);
  const [bgColors, setBgColors] = useState(['#fff', '#fff', '#fff']);
  function onMouseEnter(index) {
    setActiveIndex(index);
    if(index >= 0) {
      const imgs = document.querySelectorAll('img');
      if(imgs[index] && imgs[index].src){
        const a = colortheif.getPalette(imgs[index], 3);
        if(Array.isArray(a)) {
          setBgColors(a.map((g) => {
            return `rgb(${g[0]},${g[1]},${g[2]})`;
          }));
        }
      }
    } else {
      setBgColors(['#fff', '#fff', '#fff']);
    }
  }
  const data = new Array(4).fill(1);
  return (
    <div className={styles.container}
         style={{ // 设置渐变背景颜色
           background: `linear-gradient(to right, ${bgColors[0]}, ${bgColors[1]}, ${bgColors[2]})`,
         }}
    >
      {data.map((item, index) => {
        return (
          <div className={styles.item}
               onMouseEnter={ () => onMouseEnter(index)}
               onMouseLeave={() => onMouseEnter(-1)}
               key={index}>
            <img src={"https://picsum.photos/200/300?r=" + index}
                 crossOrigin={'anonymous'}
                 style={{
                   opacity: activeIndex === index || activeIndex < 0 ? 1 : 0.2,
                 }}
                 data-idnex={index}
            />
          </div>
        );
      })}
    </div>
  );
}
.container{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  width: fit-content;
  height: fit-content;
  gap: 20px;
  padding: 20px;
}
.item{
  width: 200px;
  height: 300px;

}
.item img{
  width: 100%;
  height: 100%;
  cursor: pointer;
  border: 2px solid #fff;
  border-radius: 10px;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值