Can not get pixel color at mouse location

edited February 2014 in Questions about Code

Can not get pixel color at mouse location if I use P2D or noLoop(). But I need to use these two in other project.

void setup() {
  size(500, 150, P2D);
  rectMode(CORNER);
  noStroke();
}

void draw() {
  for (int i=0; i< 10; i++) {
    fill((color) random(#000000));
    rect(i*50, 0, 50, 150);
  }
  noLoop();
}

void mouseClicked() {
  loadPixels();
  color c = pixels[mouseY*width+mouseX];
  println(hue(c), saturation(c), brightness(c));
}
Tagged:

Answers

  • edited February 2014 Answer ✓

    I did some tiny mods in order to run in my Processing v2.0.2 here. And all of a sudden, it was fixed alright! :-/

    // forum.processing.org/two/discussion/3321/
    // can-not-get-pixel-color-at-mouse-location
    
    //static final String ENGINE = JAVA2D;
    static final String ENGINE = P2D;
    //static final String ENGINE = P3D;
    
    void setup() {
      size(500, 150, ENGINE);
      noLoop();
      rectMode(CORNER);
      noStroke();
    }
    
    void draw() {
      for (int i = 0; i != 10; i++) {
        fill((color) random(#000000));
        rect(i*50, 0, 50, 150);
      }
    
      loadPixels();
    }
    
    void mouseClicked() {
      final color c = pixels[mouseY*width + mouseX];
      println(hue(c) + "\t" + saturation(c)+ "\t" + brightness(c));
    }
    
  • so you have to loadPixels() before executing noLoop() ?

  • Answer ✓

    I've transfered loadPixels() from mouseClicked() into draw().
    B/c there was no need to keep updating pixels[] while canvas isn't being modified anyways!

    Seems like that modification ended up being important for OPENGL modes like P2D & P3D!
    JAVA2D has a more predictable behavior and doesn't care about these strange fixes!

    And whether we place noLoop() in setup() or in draw() doesn't matter!
    Callback draw() is run at least once anyways! And also for each resize()!

Sign In or Register to comment.