I'm looking to dynamically change the background color of my components based on the colors of the images inside them. Each component should have its own unique color, but currently all 20 instances on the page are getting the same color. I've tried using inline styling and also experimented with refs and unique IDs based on `pokemonid`, but haven't had success.
The color is generated when the image is loaded in the component through a specific function.
Here's an example of the component code named pokemon-card
:
<template>
<div class="card">
<div class="card__front" :style="{'background' : `radial-gradient(circle at 50% 0%, ${cardCircleColor} 36%, #fff 36%)`}">
<div class="card__front__cardTop">
<div class="card__front__cardTop__id"><span></span>{{ id }}</div>
</div>
<img class="card__front__img"
:src="'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/' + id + '.png'"
alt="pokemonImage" crossorigin="anonymous">
<div class="card__front__name">
<h3>{{ name }}</h3>
</div>
</div>
<div class="card__back">
<router-link :to="`/pokemonDetails/${id}`" class="card__back__button">Details</router-link>
</div>
</div>
</template>
The background color is set by this method:
methods: {
//get color for background based on pokemon image
getColor() {
const fac = new FastAverageColor();
fac.getColorAsync(document.querySelector(`.card__front__img`))
.then(color => {
this.cardCircleColor = color.hex
})
},
},
mounted() {
this.getColor()
},
Corresponding CSS snippet applying the color to radial-gradient (circle at 50% 0%, # 36%, #fff 36%);
&__front {
transition: all 0.8s;
//background: radial-gradient(circle at 50% 0%, #90aac1 36%, #fff 36%);
//background-color: $cardBg_color;
Parent element:
<template>
<div class="container">
<div class="cardContainer">
<pokemon-card v-for="data in pokemonData.results" :name="data.name" :id="data.id"></pokemon-card>
</div>
<div class="PaginationcontrolContainer">
<div class="paginationControls">
<div @click="decreasePaginationCounter" class="paginationControls__btn"> < </div>
<input @change="manuallyChangingPaginationIndex" v-model="paginationIndex" type="number">
<div @click="increasePaginationCounter" class="paginationControls__btn"> > </div>
</div>
</div>
</div>
</template>