背景跟随图片改变

下载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>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值