How do I get pixels to display ONE by ONE after a key is pressed?

Hello all,

I’m new to processing and I’ve got a question about pixels. I want to write a program in which the user can press a key and if a key is pressed, ONE pixel of an image appears. Right now, if I press a key, the whole image appears immediately. I can’t wrap my head around how to fix this, although it feels kinda stupid.
I copied code from a Youtube video from Daniel Shiffman (The Coding Train) and want to make this small adjusment. Can anybody help me? Thanks in advance!!

PImage img;

void setup() {
  size(1565,1037);
  img = loadImage("voorbeeld.JPG");
}

void draw() {
  loadPixels(); 

  img.loadPixels(); 
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int loc = x + y*width;
          
      float r = red(img.pixels[loc]);
      float g = green(img.pixels[loc]);
      float b = blue(img.pixels[loc]);
      
      if(keyPressed) {
        pixels[loc] =  color(r,g,b);    
      }
    }
  }
  updatePixels();
}
1 Like

I’m assuming that each time the key is pressed, an additional pixel appears? Like, building up the image over time?

There are a few ways to approach such a problem.

One is to draw only that pixel when that key is pressed – never refresh the sketch (don’t use background) and let the pixels accumulate on the surface. Pressing the key will draw pixels[0], then again pixels[1], then pixels[2], etc.

Another way is to draw as many pixels as you should, each draw frame. First wipe the screen. Now, how many times has the key been pressed? If 5, draw five pixels. If 136, draw 136 pixels.

Rather than looping through x and y, the easier way to do this is to loop over pixels, and then draw each pixel to its x/y location. To do this, you need to know your image width/height.

If you know the x,y, then pixelnum = y*width+x
If you know the pixelnum, then pixelx = pixelnum - pixelnum%width
and pixely = (pixelnum - pixelx)/width

So, you can count the keystrokes (137) and then loop over pixels and draw the first 137 pixels. If you width is 100x100, then pixel #137 is at (36, 1).