<template>
    <div>
        <div>
            在vue中获取图片的主色调
            <a href="https://lokeshdhakar.com/projects/color-thief/">官网传送门</a>
            <p>本次仅讲局部引入的方式</p>
            <p>安装:npm i --save colorthief</p>
        </div>

        <img id="background" :src="url" height="100" width="100" crossorigin="anonymous"/><!--后面的属性允许获取网络上的图片-->
        <ul class="show">
            <li v-for="color in colors" :style="{background:`rgb(${color.toString()})`}">
                <!--                rab:{{color.toString()}}-->
            </li>
        </ul>
    </div>
</template>

<script>
    import ColorThief from "colorthief";

    export default {
        name: "Color",
        data() {
            return {
                url: '',
                colors: [],
                //210042 449818741 1442312981
            }
        },
        methods: {
            ImgColor() {
                this.$axios.get(`https://autumnfish.cn/song/detail`,
                    {params: {ids: 210042}}).then((song) => {
                    this.url = song.data.songs[0].al.picUrl;
                    let domImg = document.querySelector('#background');
                    let colorthief = new ColorThief();
                    domImg.addEventListener('load', () => {
                        console.log('加载好了并取色', colorthief.getPalette(domImg, 2));//第二个参数可选(1~10)
                        this.colors = colorthief.getPalette(domImg);
                    })
                })
            }
        },
        mounted() {
            this.ImgColor();
        }
    }
</script>

<style scoped>
    * {
        padding: 0;
        margin: 0;
        list-style: none;
    }

    a {
        color: #835cff;
        text-decoration: none;
    }

    img {
        border-radius: 15px;
    }

    .show > li {
        width: 100px;
        height: 30px;
        border-radius: 15px;
    }
</style>

效果图:

在vue中获取图片主色调效果图

 

 

 

 

Logo

前往低代码交流专区

更多推荐