Get all children from SVG

Hi Everyone.
I came back to processing after a few years of not coding anything and I am struggling with something I think I could do before.

I’m looking to draw SVGs with the flexibility of changing the colours of the elements inside. Because different SVGs have different amount of elements I need to be able to fetch those elements dynamically.
I know I can get a set of elements by using getChild(“Name”) but that works when I have the names only.

I’ve arrived at this code which prints separate graphic elements but for some reason, it’s not drawing them. This example uses very common the bot1.svg

import processing.svg.*;

PShape[] children;
PShape sh;

void setup() {
  size(800, 800);

  sh = loadShape("bot1.svg");
  shapeMode(CENTER);
  strokeWeight(1);
}
void draw(){
  children = new PShape[sh.getChildCount()];
  push();
  translate(width/2, height/2);
  //shape(sh,0,0,400,400);
  //children = sh.getChildren();
  
  for (int s = 0 ; s <children.length; s++) {
      children[s] = sh.getChild(s);
      children[s].disableStyle();
      children[s].fill(0);
      shape(children[s], 0, 0, 100, 100);
      println(children[s]);
    
  }
  
  pop();
}

Try this in your setup :

sh = loadShape("bot1.svg");
sh.disableStyle();
children = sh.getChildren();

and in your draw

shape(children[s], 0, 0, 100, 100);

How would it work if I am changing the original svg in the draw from a pool of svgs (which I didn’t specify as my requirement, but that’s the end goal)

Unfortunately didn’t work.

First question : put this code in a function than you use when you need
Second question : it’s maybe the structure of your .svg that have too many node,
if you can make it simplest as possible

Tried this simpler one tram-01.svg - Google Drive and still didn’t work.

This work for me :

PShape sh;
PShape[] children;
void setup() {
    size(256, 256);
    sh = loadShape("tram-01.svg");
    sh.disableStyle();
    children = sh.getChildren();
}
void draw() {
    for(int s=0; s<children.length; s++){
        shape(children[s], 0, 0);        
    }
}
1 Like

I must’ve been doing something wrong. That works for me too!

I understand why it wasn’t working. This is a problem I’ve been having too. For some reason shape doesn’t allow size when drawing children.

1 Like