Pixel Sorter

This sketch sorts the pixels in an image, so that lighter pixels float to the top and darker pixels sink to the bottom.


This is a companion discussion topic for the original entry at https://happycoding.io/examples/p5js/images/pixel-sorter

Hi! I was wondering how it would be possible to have this sort of pixel adjustment continue indefinitely, either through some other sorting algorithm or through looping? Is there a direction in which you could point me?

Thanks!

1 Like

That’s a fun idea. You could do something like create a variable at the top of the sketch, maybe something like:

let darkSinks = true;

Then use that variable in the sortPixels() function. If the variable is true, then make darker pixels sink, but if it’s false make them float, reversing the direction of the animation.

Then you could flip the value of that variable, either after a certain amount of time, or when the user clicks the mouse, or when no pixels have moved in X frames.

I’d start with something like that, and then you can branch out into more complex ideas. But the pattern will be similar: create some variables at the top of the sketch, use those variables when you’re moving the pixels around, and then change those variables to when you want the animation to change.

Good luck! I’d love to see what you come up with!

Wow, thank you so much for your fast and thorough response!! I don’t know how much time you have, but I’m a very new coder – is there any chance you could elaborate on how to flip the variable based on time?

Thank you again!

Sure. There are a few ways to do it, for example using the frameCount variable or the millis() function, but here’s an example that flips an animation every 120 frames:

let falling = true;
let circleY = 100;
let framesSinceFlip = 0;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  // Move the circle
  if(falling){
    circleY++;
  } else{
    circleY--;
  }
  
  // Draw the circle
  circle(width/2, circleY, 50);
  
  // Keep track of how long it's been since the animation flipped
  framesSinceFlip++;
  
  // Flip the animation every 120 frames
  if(framesSinceFlip > 120){
    falling = !falling;
    framesSinceFlip = 0;
  }
}

That shows a circle bouncing up and down, but you could apply the same pattern to any animation.