Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SVG File With Dynamic Fill Colors – Vue

I am making a twitter clone application with VueJS 3.

I saved Twitter’s logo as a .svg file and can use it with the <img /> tag. I can also change its color when I give the <svg> tag the fill="#fff" attribute. However, I want to use this .svg file in multiple places and in different colors.

So I tried to dynamically change the color of the svg by giving the <img /> tag the classes fill-white, bg-white and text-white, but it didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My Currently .svg File – With White Color

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" aria-hidden="true">
    <g>
        <path fill="#fff" d="M23.643 4.937c-... 1.7-1.477 2.323-2.41z"></path>
    </g>
</svg>

Img Tag

<img
 src="/twitter-bird.svg"
 draggable="false"
 class="w-52 lg:w-96 fill-white"
 alt="Twitter Bird"
/>

I Tried This On .svg File

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" aria-hidden="true">
    <g>
        <path fill="params(fill) #fff" d="M23.643 4.937c-... 1.7-1.477 2.323-2.41z"></path>
    </g>
</svg>

I understand that I need to make this svg’s color editable. But I couldn’t find how to do this.

>Solution :

You can make component from svg file and bind fill to prop:

const app = Vue.createApp({
  data() {
    return {
      colors: ['#8A2BE2', 'rgb(255,255,0)', '#008000'],
    };
  },
})
app.component('myImg', {
  template: `
    <svg height="40" viewBox="0 0 107.1 107.1" style="enable-background:new 0 0 107.1 107.1;" xml:space="preserve">
    <path :fill="color" d="M2.287,47.815l23.096,19.578L18.2,96.831c-1.411,5.491,4.648,9.998,9.575,6.901L53.55,87.813l25.774,15.916   c4.79,2.955,10.844-1.408,9.576-6.902l-7.184-29.435l23.099-19.579c4.363-3.661,2.111-10.844-3.662-11.267l-30.282-2.255   L59.464,6.266c-2.112-5.211-9.577-5.211-11.832,0L36.225,34.292L5.944,36.547C0.174,37.113-2.081,44.154,2.287,47.815z"/>
  </svg>
  `,
  props: ['color']
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="col in colors">
    <my-img :color="col"></my-img>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading