安装 npm i colorthief
效果
代码
<template> <div> <img ref="image" src="@/assets/img/no-message.png" alt="示例图片"> <button @click="getColorPalette">获取颜色</button> <div>主色调</div> <br/> <div class="color" :style="{ background: color }"></div> <br/> <div>调色板</div> <ul> <li v-for="color in colorPalette" :key="color" :style="{ background: color }"> {{ color }} </li> </ul> </div> </template> <script setup> import { ref } from 'vue' import ColorThief from 'colorthief'; const image = ref(null); const colorPalette = ref([]); const color = ref('') const getColorPalette = () => { const img = image.value; const colorThief = new ColorThief(); if (img) { const mainColor = colorThief.getColor(img);//主色调 color.value = `rgb(${mainColor[0]}, ${mainColor[1]}, ${mainColor[2]})` const palette = colorThief.getPalette(img);//获取调色板 colorPalette.value = palette.map(([r, g, b]) => `rgb(${r}, ${g}, ${b})`); } }; </script> <style lang="scss" scoped> .color { width: 50px; height: 50px; } ul { list-style: none; padding: 0; display: flex; flex-wrap: wrap; } li { width: 50px; height: 50px; margin: 5px; border-radius: 5px; } </style>View Code
官网 https://lokeshdhakar.com/projects/color-thief/
详细教程推荐参考
https://blog.csdn.net/qq_64546210/article/details/144011160
https://blog.csdn.net/m0_46281382/article/details/142087154
标签:const,img,color,50px,ColorThief,介绍,vue3,ref From: https://www.cnblogs.com/yflbk-2016/p/18619668