mercredi 15 mai 2019

How to make a random color function acting on svg groups call the same color for all elements in group

I have a function that creates a random color. I use this function in another function to call the color onclick of an svg groups. The problem is that all elements in the group get a random color, whilst it should be one random color for all elements in the group.

I have tried tweaking the function that calls the color. And I don't manage to tweak the random function properly.

function call1(){
const children = document.getElementById('btn1').children;
for(let i = 0; i < children.length; i++ ){
  children[i].setAttribute('fill',getRandomColor());
} 
}

function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
  color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

  
  function setRandomColor() {
$("#colorpad").css("background-color", getRandomColor());
  }
#svg-object{
    
        height: 100vh;    
        width: 100%;
        background-size: cover;
        background-position: center center;
        border: 15px antiquewhite;
        position: absolute;
    
}
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg id="svg-object" version="1.1" xmlns="http://www.w3.org/2000/svg" 
 xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="800px" height="754px" viewBox="0 0 800 754" enable- 
 background="new 0 0 800 754" xml:space="preserve">
<g id="btn1" onclick="call1()">
        <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131       "/>
        <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656       
 "/>
        <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656       
"/>
        <polygon points="366.699,581 410,656 453.301,581     "/>
</g>


</svg>

I expect all the elements in the group to change to one random color.``




Aucun commentaire:

Enregistrer un commentaire