当前位置: 首页 > news >正文

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;
}
http://www.dtcms.com/a/150749.html

相关文章:

  • 从GPT-5到Claude 3:大模型竞赛的下一站是什么?
  • 【ROS2】机器人操作系统安装到Ubuntu简介
  • 基于STM32、HAL库的MCP42010T数字电位器驱动程序设计
  • WebGL简介
  • rust编程学习(三):8大容器类型
  • Transformer 零基础实践教程 - 0 - 前言与环境配置
  • Rust 学习笔记:Rust 简介
  • element-ui transfer 组件源码分享
  • 远程控制Firefox浏览器实例的挑战与Playwright的CDP和Selenium Marionette解决方案
  • STM32 SysTick定时器
  • ElasticSearch:高并发场景下如何保证读写一致性?
  • 11、认识redis的sentinel
  • 神经网络相关内容
  • SpringBoot中6种自定义starter开发方法
  • Hadoop 集群扩容新增节点操作文档
  • Java 实现SpringContextUtils工具类,手动获取Bean
  • 鸿蒙NEXT开发网络相关工具类(ArkTs)
  • node.js 实战——(概念以及Buffer 知识点学习)
  • 数据结构线性表的顺序存储结构
  • openEuler安装nvidia驱动【详细版】
  • 外贸获客新革命:基于AI的搜索引擎排名攻防战——48小时抢占谷歌TOP3的技术逻辑与实战路径
  • 基于VUE+Node.JS实现(Web)学生组队网站
  • LInux平均负载
  • maven中pom.xml setting.xml关系
  • 二叉树OJ题目
  • 大模型框架技术全景与下一代架构演进
  • 如何批量为多张图片(JPG、PNG、BMP、WEBP 等格式)添加自定义水印保护
  • C++ 容器查找效率
  • 20250423修改和查看荣品的PRO-RK3566开发板的buildroot linux系统的cpu频率
  • Linux命令-sar