colorthief官网
https://lokeshdhakar.com/projects/color-thief/#examples
安装
npm i --save colorthief
yarn add colorthief
使用案例
<template>
<div class="box app" :style="{ background: bodyBgColor }">
<div class="img-item" v-for="(img, index) in imgArr" :key="index" @click="imgClick(index)">
<img :src="img" class="box" ref="img" />
</div>
</div>
</template>
<script>
import Colorthief from 'colorthief';
export default {
data(){
return {
imgArr: [
require('@/images/img1.jpeg'),
require('@/images/img2.jpg'),
require('@/images/img3.jpg'),
require('@/images/img4.jpg'),
require('@/images/img5.jpg')
],
bodyBgColor: '#fff'
}
},
methods: {
async imgClick(i){
const colorthief = new Colorthief();
const imgElem = this.$refs.img[i];
const colors = await colorthief.getPalette(imgElem, 3);
this.bodyBgColor = `linear-gradient(rgb(${colors[0].join(',')}), rgb(${colors[1].join(',')}), rgb(${colors[2].join(',')}))`;
}
}
}
</script>
<style>
*{
padding: 0;
margin: 0;
}
html, body, .box {
width: 100%;
height: 100%;
}
.app{
display: flex;
align-items: center;
}
.img-item{
height: 300px;
flex: 1;
border: 4px solid #f5f5f5;
cursor: pointer;
}
</style>
图片案例