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

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.xdnf.cn/news/1427.html

相关文章:

  • 【Java学习笔记】选择结构
  • 4月23日作业
  • 聊聊自动化用例的维护
  • Java 实现单链表翻转(附详细注释)
  • PH传感器详解(STM32)
  • 配置kafka与spark连接
  • 标题:掌握 PowerShell 防火墙管理:C# 中的高效操作指南
  • Kafka 核心使用机制总结
  • vue实现静默打印pdf
  • Redis 详解:安装、数据类型、事务、配置、持久化、订阅/发布、主从复制、哨兵机制、缓存
  • 华为AR1200 telnet设置
  • zkPass案例实战之合约篇
  • 使用react的ant-design-pro框架写一个地图组件,可以搜索地图,可以点击地图获取点击的位置及经纬度
  • 彻底禁用windows的语音识别快捷键win+ctrl+s
  • 【计算机视觉】CV项目实战- SORT 多目标跟踪算法
  • 融山科技前端面经
  • Fabric.js 设置画布背景
  • OpenCV 图形API(57)颜色空间转换-----将图像从 RGB 色彩空间转换为 YUV 色彩空间函数RGB2YUV()
  • Ragflow、Dify、FastGPT、COZE核心差异对比与Ragflow的深度文档理解能力​​和​​全流程优化设计
  • python后端程序部署到服务器 Ubuntu并配合 Vue 前端页面运行
  • 【CSS】层叠,优先级与继承(四):层叠,优先级与继承的关系
  • 电液伺服高频应力腐蚀疲劳试验机
  • 长连接、短连接与WebSocket的基本知识
  • Lua 第9部分 闭包
  • uv pip install 的本质是什么?
  • 十大物联网平台-物联网十大品牌
  • Java高级:数据库访问优化
  • 量子混合计算革命:Qiskit 3.0开启云上量子开发新时代
  • 不开启手机调试模式如何开发自动化脚本?
  • 【go】方法与函数区别,函数的内联与逃逸分析