javascript – Change some colors of SVG used as background image-ThrowExceptions

Exception or error:

I have looked through a lot of answers related to changing the colours of SVG as a background image but all doesn’t suit my case.

I want to change some colours (not all), in my SVG image. So my SVG has some path with unique classes and those are the ones I want to change.

I use SCSS and dynamically pass colours to my component via CSS variables.

In my component SCSS, I have a function that will pass the dynamic styles to the SVG

// check if a custom colour is available
@function dynamic_color() {
    $custom-color: var(--primary-svg-color);
    @if $custom-color{
      @return #{$custom-color};
      @return 263236;

This is how I am passing it to the SVG image (notice how i pass the dynamic_color() )

background-image: url("data:image/svg+xml, %3Csvg xmlns='' width='768.762' height='462.909' viewBox='0 0 768.762 462.909'%0A%3E%3Cdefs%3E%3Cstyle%3E .a %7B fill: %23e0e0e0; %7D .b %7B fill: %23fafafa; %7D .c %7B fill: %23ebebeb; %7D .d %7B opacity: 0.368; %7D .e %7B fill: %23f5f5f5; %7D .f %7B fill: %23263238; %7D .g %7B fill: %23455a64; %7D .h %7B fill: %23#{dynamic_color()} %7D .i....")

The SVG is encoded to base64 and dynamic_color() is passed to the class I want to dynamically fill.

The if statement in the dynamic_color function works but it doesn’t render the colour (Very sure the colour is available if not the if statement should not work), but if I hardcode a colour it works.

I don’t know why and what could be the possible solution. Also, I have a concern about using the SVG as an encoded base64… is this the best way to use SVGs as a background image? what could be the most efficient solution?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *