Class and background image

Hello.
I wrote a code using functions and had a background image written like that:

PImage bg;

Void setup() { 
  size (600,400);
  bg =  loadimage(“floral.jpg”);
}

Void draw() {
  background(bg);
  stroke(0);
} 

However, now I’m trying to convert everything to a class and not sure where to put the background image. Because when it’s in void setup, along with the size, it says that variable bg doesn’t exist. Although I declared it by saying PImage = bg.

If someone could please give any advice I’d appreciate it a lot.

Thanks!

1 Like

There’s no Void keyword in Java. It’s void instead:

It’s not loadimage() but loadImage():

You can do something like this example:

static final String IMG_FILENAME = "floral.jpg";
BackgroundImage bgImg;

void setup() {
  size(600, 400);
  stroke(0);

  bgImg = new BackgroundImage(loadImage(IMG_FILENAME));
}

void draw() {
  bgImg.show();
}

class BackgroundImage {
  PImage bg;

  BackgroundImage(final PImage img) {
    bg = img;
    fitToCanvas();
  }

  BackgroundImage fitToCanvas() {
    bg.resize(width, height);
    return this;
  }

  BackgroundImage show() {
    background(bg);
    return this;
  }
}
1 Like

Okay so it worked when I created separate class for the background. Thank you!