下载colorthief
npm i colorthief
<script setup>
import { ref } from 'vue'
import ColorThief from 'colorthief'
const urls = [
'https://tse3-mm.cn.bing.net/th/id/OIP-C.Md86Wi2EYiKHNPldRZiD4gHaEo?w=289&h=180&c=7&r=0&o=5&pid=1.7',
'https://tse1-mm.cn.bing.net/th/id/OIP-C.dIFgv5Jaess7oclRS7xg2wHaE8?w=278&h=185&c=7&r=0&o=5&pid=1.7',
'https://tse2-mm.cn.bing.net/th/id/OIP-C.99mW3d7ITdJm8m-XnnRQRwHaEe?w=305&h=185&c=7&r=0&o=5&pid=1.7',
'https://tse3-mm.cn.bing.net/th/id/OIP-C.oE-0dG4KZ2588LRzUO_lmAHaEo?w=289&h=180&c=7&r=0&o=5&pid=1.7',
'https://tse2-mm.cn.bing.net/th/id/OIP-C.pEOYW895J4IeO6tPq1L2HwHaEo?w=294&h=183&c=7&r=0&o=5&pid=1.7'
]
const colorthief = new ColorThief()
const hoverIndex = ref(-1)
const mainRef = ref()
async function handleMouseEnter(img, i) {
hoverIndex.value = i
const color = await colorthief.getPalette(img, 3)
const [c1, c2, c3] = color.map((item) => {
return `rgb(${item[0]},${item[1]},${item[2]})`
})
mainRef.value.style.setProperty('background', `linear-gradient(${c1}, ${c2},${c3})`)
}
function handleMouseLeave() {
hoverIndex.value = -1
mainRef.value.style.setProperty('background', 'white')
}
</script>
<template>
<div class="main" ref="mainRef">
<img
v-for="(o, i) in urls"
:key="o"
crossorigin="anonymous"
:src="o"
alt=""
@mouseenter="handleMouseEnter($event.target, i)"
@mouseleave="handleMouseLeave()"
:style="{
opacity: hoverIndex === -1 ? 1 : i === hoverIndex ? 1 : 0.2
}"
/>
</div>
</template>
<style scoped>
.main {
width: 100vw;
height: 100vh;
overflow: hidden;
display: flex;
justify-content: space-around;
align-items: center;
}
img {
border-radius: 10px;
overflow: hidden;
}
img:hover {
transform: scale(1.1);
border: 2px solid white;
box-shadow: 0 0 10px white;
}
</style>