Skip to main content

Detect color with colorjs.io in Vue

·159 words·1 min
Shadowfish
Author
Shadowfish
Welcome to my digital space. Check out my recent work and posts below.

Ever wanted to assign a color depending on what color is prominent in an image?

Now you can with color.io!

color-cards

I wanted to use images in small cards with and use the most prominent color in that image. Then use the color as backgrounds or gradients.

const { prominent } = require('color.js')

async getColorByImageUrl(imgUrl) {
    // Pass image url to prominent method
    const textColor = await prominent(imgUrl, { amount: 1 }).then(color => {
    const rgbString = `rgb(${color})`

    // Get the prominent color as RGB (Usable if you need opacity)
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(color);
        }, 100);
    });
    }).then(data => {
        // Get the selector in the DOM that you wish to manipulate
        const el = document.querySelector('.' + this.data.slug + '-bg');
        
        // In my implementation I wanted to set a gradient based on what color is detected in an image
        if(el) {
            el.style.background = `linear-gradient(rgba(${data},0) 0%, rgba(${data},0.9) 60%,rgba(${data},0.9) 80%, rgba(${data},0.99) 100%)`;
        }
        return data
    });
}