dimanche 29 septembre 2019

Apply random color to each path without new function for each

I have an SVG with a bunch of paths (rect here for simplicity)

<rect id=1 x="0" y="100" width="100" height="100"/>
<rect id=2 x="120" y="100" width="100" height="100"/>
<rect id=3 x="240" y="100" width="100" height="100"/>

I have my snippet which defines my colors:

var colors = ['red','yellow','green','blue','orange','purple','black','white'];

Then comes the snippet which randomizes the color

var random_color1 = colors[Math.floor(Math.random() * colors.length)];
var random_color2 = colors[Math.floor(Math.random() * colors.length)];
var random_color3 = colors[Math.floor(Math.random() * colors.length)];

Then I have this which applies the random color to each path (each has a unique id)

document.getElementById('1').style.fill = random_color1;
document.getElementById('2').style.fill = random_color2;
document.getElementById('3').style.fill = random_color3;

The thing is, I have a few hundred paths in this document. I need to apply the randomize to each and every path, my current process leaves hundreds of lines of code.

I'm looking for a way to;

  1. Not need a unique path id for each path
  2. Call the random_color function each time for a path without creating a new one per path and then apply it to that path.

I'm really new to javascript and I've tried whatever I know, but to no avail.




Aucun commentaire:

Enregistrer un commentaire