Conditional background() of an image in draw() fails on OS X.

Running in to a strange problem with p5 0.6.1 on the Mac -- I can get a background image to load sometimes but not others. The same script loads just fine on my Win8 VMWare partition, I'm using Firefox in OS X and Win8.

var bg;
var backgroundLoaded = false;

function setup() {
  bg = loadImage("assets/moonwalk.png");
  createCanvas(720, 400);
}

function draw() {
  // this works, loads the background image on every cycle and overrwites my ellipses:
  // background(bg);

  if (backgroundLoaded == false) {
    // this works, turns the screen red, ellipses are not overwritten
    // background(255, 0, 0);
    // but this gives me a white screen:
    background(bg);
    backgroundLoaded = true;
  }

  ellipse(mouseX, mouseY, 10);
}

Answers

  • Are you sure the image is loaded by the time you try to draw it?

    You might try using the preload() function:

    var bg;
    function preload() {
      bg= loadImage('assets/moonwalk.png');
    }
    
    function setup() {
      createCanvas(720, 400);
      background(bg);
    }
    

    More info here: https://github.com/processing/p5.js/wiki/p5.js-overview

    Also note that I've moved the call to background() into the setup() function, which is an easier way to do something only once at the beginning of the sketch.

  • preload() fixes things on my Mac, thanks.

    The conditional is because the student is going to be changing the background image and resetting backgroundLoaded to false based on mouse activity.

Sign In or Register to comment.