Skip to content

Color thief for user avatars #251

@fabianschultz

Description

@fabianschultz

Hi, I like the idea of showing shadows based on dominant colour below images. Looks pretty beautiful!
My question is, how can I achieve this for websites like BuddyBoss or BuddyPress? Users/members can upload images which are then shown on directory page. So in other words many user avatars/images can be side by side.

So far I can achieve to get the shadow for 1 image but not for all of them:
`<script>
function applyShadowToAvatar() {
// Get user ID from the image URL
const userIdMatch = /avatars/(\d+)//.exec(document.querySelector('.avatar.user-7-avatar.avatar-300.photo').getAttribute('src'));
if (!userIdMatch) return;

    const userId = userIdMatch[1];

    // Create an image element
    const image = new Image();

    // Set the image source to trigger loading
    image.src = `https://stefanpfadt.de/wp/wp-content/uploads/avatars/${userId}/654a1f543a8a9-bpfull.jpg`;

    // Event handler for image load
    image.onload = function () {
        // Create a canvas element to extract the dominant color
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, 1, 1);

        // Get the color data of the single pixel
        const colorData = context.getImageData(0, 0, 1, 1).data;

        // Extract the RGB values
        const dominantColor = [colorData[0], colorData[1], colorData[2]];

        // Log the dominant color to the console
        console.log('Dominant Color:', dominantColor);

        // Apply a simple shadow color to the image
        const shadowColor = `rgba(${dominantColor[0]}, ${dominantColor[1]}, ${dominantColor[2]}, 0.5)`;
        const avatarImage = document.querySelector('.avatar.user-' + userId + '-avatar.avatar-300.photo');
        avatarImage.style.boxShadow = `0 4px 10px 0 rgba(18,43,70,.12), 0 0 0 2px var(--bb-content-border-color), 0 10px 20px ${shadowColor}`;
        console.log('Shadow Applied:', avatarImage.style.boxShadow);
    };
}

// Run the function after a short delay to ensure the DOM is fully loaded
setTimeout(applyShadowToAvatar, 2000);
</script> ` Any suggestion? Thank you :)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions