背景跟随图片的变化而变化——颜色聚合算法
效果如下
一、实现思路
通过 js 来获取图片的移动或离开,并通过 colorThief 来获取图片主要的三色元素
二、相应操作
1.html布局
采用 grid 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>背景根据图片改进(颜色聚合算法)</title>
</head>
<body>
<div class="contain-body">
<div class="body">
<div>
<img src="./images/1.jpeg" alt="" srcset="">
</div>
<div>
<img src="./images/2.jpeg" alt="" srcset="">
</div>
<div>
<img src="./images/3.jpeg" alt="" srcset="">
</div>
<div>
<img src="./images/4.jpeg" alt="">
</div>
</div>
</div>
<!-- cdn的方式 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
<!-- npm 直接安装并导入 -->
</body>
</html>
2.css
主要采用 css的变量——形式如:color: var(上面定义的变量名)
* {
margin: 0;
padding: 0;
}
html {
--c1: #fff;
--c2: #fff;
--c3: #fff;
background-image: linear-gradient(var(--c1), var(--c2), var(--c3));
}
.contain-body {
width: 100%;
height: 100vh;
}
.body {
margin: auto;
width: 1200px;
height: 800px;
/* background-color: pink; */
display: grid;
grid-template-columns: repeat( 2, 1fr);
grid-template-rows: repeat(2, 1fr);
/* grid-gap: 40px; */
justify-items: center;
align-items: center;
}
.body div {
width: 520px;
height: 318px;
overflow: hidden;
border-radius: 5px;
transition: all 0.6s;
}
img {
width: 100%;
height: 100%;
}
.mouseenter {
width: 530px !important;
height: 328px !important;
padding: 10px;
box-shadow: 1px 1px 19px 3px #000000;
}
.opacity {
opacity: 0.15;
}
3.js
采用颜色聚合算法来算出图片的主要三个颜色像素
<script>
// 引入 colorthief
const colorThief = new ColorThief();
const html = document.documentElement; // 通过html来设置属性
// 通过 js 来首先图片的放大和还原来
let divs = document.querySelector(".body").querySelectorAll("div")
for (const iterator of divs) {
iterator.addEventListener("mouseenter", () => {
divs.forEach((e) => {
e.classList.remove("mouseenter")
e.classList.add("opacity")
});
// console.log(iterator);
// 使用取色器来获取图片的主要颜色 :第三方API colorthief
// colorThief.getPalette => 返回的是一个回调函数 | colors 为一个二维数组
let colors = colorThief.getPalette(iterator.querySelector("img"), 3); // 该API只有两个函数,第一个getColor只获取第一个,getPalette获取你想要得到多少个参数的rgb
// console.log(colors);
const [c1, c2, c3] = colors.map((c) => `rgb(${c[0]},${c[1]},${c[2]})`);
// console.log(c1, c2, c3);
html.style.setProperty('--c1', c1)
html.style.setProperty('--c2', c2)
html.style.setProperty('--c3', c3);
// console.log(colors);
iterator.classList.add("mouseenter")
iterator.classList.remove("opacity")
})
iterator.addEventListener("mouseleave", () => {
html.style.setProperty('--c1', '#fff')
html.style.setProperty('--c2', '#fff')
html.style.setProperty('--c3', '#fff');
iterator.classList.remove("mouseenter")
// iterator.classList.add("opacity")
divs.forEach((e) => {
e.classList.remove("opacity")
})
})
}
</script>