简体   繁体   中英

Change colour of SVG loaded from file

I have an SVG loaded from file in an tag like so...

<img class="svgbutton" src="filepath/icon.svg">

the svg is just a simple icon in a single colour. Is it possible to control the colour of the svg in someway (possibly a filter?), either using css or javascript?

Or is the only proper way to do this to draw it fully in the script..?

I suggest to use inline SVG like this in HTML:

<div style="color: red;">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        [ ... ]
    </svg>
</div>

By doing so you may use standard CSS (and JavaScript if required for dynamic changes, but keep in mind that there are pseudo-classes to style mouse-over and much more). The trick here is to apply the inherited CSS color to the SVG fill color with fill: currentColor;

<style type="text/css">
    svg {
        fill: currentColor;
    }
</style>

You could also keep multiple symbols together, hide thie whole "collection" with CSS display: none; on the <svg ...> element and reuse the symbols separately in multiple places.

A symbol definition in the "collection":

<g id="icon1">
    <path class="path1" d="M22 20c-2 2-2 4-4 4s-4-2-6-4-4-4-4-6 2-2 4-4-4-8-6-8-6 6-6 6c0 4 4.109 12.109 8 16s12 8 16 8c0 0 6-4 6-6s-6-8-8-6z"></path>
</g>

Use it anywhere like this:

<svg viewBox="0 0 64 64">
    <use xlink:href="#icon1"></use>
</svg>

NOTE: xlink:href is deprecated as of SVG 2.0 and is being replaced by href which might not yet be supported by your browser though...

You could also color multiple paths in one symbol differently:

<style type="text/css">
    .path1 {
        color: blue;
        fill: currentColor;
    }
</style>

Keep experimenting with classes and pseudo-classes before choosing JavaScript for dynamically changing your element's classes as it might not be necessary.

This can require some Javascript or Jquery, often a bit tricky.

The simpliest way that I can think about that may work is this CSS code:

.element {
    -webkit-mask: url(yourimage.svg) center / contain no-repeat;
    background: red;
}

However, some browers do not support this, there are fallbacks though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM