Home > database >  Is there a way I can fill different color inside SVG image using HTML (currently using d3.js)
Is there a way I can fill different color inside SVG image using HTML (currently using d3.js)

Time:05-26

I have a SVG which needs to be filled as per data just like this image. I need to fill arms with different color, head with different color and legs with different color, that all using HTML, CSS and JavaScript. I'm currenlty using it on Angular which also uses D3.js. Is there any work around of this?

CodePudding user response:

You can just give the SVG some classes and toggle them using JS or edit the elements fill style.

const colors = ['red', 'blue', 'green', 'yellow', 'gray']
setInterval(() => {
document.getElementById('hair').style.fill = colors[Math.floor(Math.random() * colors.length)];
}, 200)
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" width="100px" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 511.999 511.999" style="enable-background:new 0 0 511.999 511.999;" xml:space="preserve">
<g>
    <path id="hair" d="M410.439,0c0,0-18.211,44.138-141.241,44.138h-79.448c0,0-123.586-6.073-123.586,105.931v82.476
        c0,31.974,12.703,62.632,35.31,85.248h300.138l6.294-6.294c19.474-19.482,31.921-45.047,34.648-72.466
        C458.629,77.674,410.439,0,410.439,0"/>

    <path style="fill:#FDD7AD;" d="M101.473,194.207c0-7.318,1.474-14.292,4.158-20.63c10.099-23.905,38.391-33.66,62.791-24.832
        c13.294,4.811,38.179,10.152,83.121,10.152s69.826-5.341,83.121-10.152c24.399-8.828,52.683,0.927,62.791,24.832
        c2.675,6.347,4.158,13.312,4.158,20.63l0.238,80.446c0,55.428-4.317,116.401-46.133,156.089
        c-14.989,14.239-32.653,25.203-49.717,36.776c-17.064,11.564-32.106,26.827-54.219,26.827s-37.155-15.263-54.219-26.827
        c-17.055-11.573-34.719-22.537-49.717-36.776c-41.807-39.689-46.371-101.667-46.371-157.087V194.207z"/>

</svg>

CodePudding user response:

Since SVGs are just markup that can be written directly into HTML, they can also have attributes such as classes and IDs, so you can just style them like you would regular elements.

You can also target them with JS to add/remove attributes etc.

Here is a super simple example of a styled SVG to illustrate:

#rect-1 {
  fill: red;
}

#rect-2 {
  fill: green;
}

#rect-3 {
  fill: blue;
}

#rect-4 {
  fill: yellow;
}
<svg>
  <rect id="rect-1" x="0" y="0" width="10" height="10" />
  <rect id="rect-2" x="0" y="20" width="10" height="10" />
  <rect id="rect-3" x="20" y="20" width="10" height="10" />
  <rect id="rect-4" x="20" y="0" width="10" height="10" />
</svg>

  • Related