P5 JS random/shuffle pixels

Hello,

I’m new in P5JS.
I’m trying to convert my Processing code to P5JS.

The question is this:
I made a Processing code that loads all pixels of an image, apprends the colors of that pixels and then shuffle them. The idea is that the image appears on the screen as a disarmed headbreaker.

Here is a video of my Processing application:
https://www.youtube.com/watch?v=Gr_sAAxdxvE

But I do not know how to do that with P5JS…
Now I’m only trying to print the image saving all pixels one by one and print it in its correct position (in the final code I shuffle that pixels).


Here is my Processing code (it works):

PImage img;

void setup() {
  size(720,1280);
  img = loadImage("san.jpg");
}

void draw() {
  background(0);
  loadPixels(); 
  for (int y = 0; y < 540; y++) {
    for (int x = 0; x < 540; x++) {
      int loc = x + y*540;
      float r = red(img.pixels[loc]);
      float g = green(img.pixels[loc]);
      float b = blue(img.pixels[loc]);
      fill(r,g,b);
      noStroke();
      rect (x,y,1,1);
    }
  }
}

Here is my P5JS code (it does not work):

var img;

function preload() {
  createCanvas(540,540);
  img = loadImage('assets/san.jpg'/*, function(img)
  {
    image(img, 0, 0);
  }*/);
}

function setup() {
  background(0);
  loadPixels(); 
  for (var y = 0; y < 540; y++) {
    for (var x = 0; x < 540; x++) {
      var loc = x + y*540;
      var r = red(img.pixels[loc]);
      var g = green(img.pixels[loc]);
      var b = blue(img.pixels[loc]);
      fill(r,g,b);
      noStroke();
      rect (x,y,1,1);
    }
  }
}

6346: Uncaught Error: Needs p5.Color or pixel array as argument.

I do not unidertand the error.
Do you know how to fix it?

Thanks!!
P.S: Sorry for my english :slight_smile:

Hey,

Your error comes from the fact that in p5.js, pixels are encoded like this :

img.pixels = {
//first pixel r,g,b,alpha
0,255,0,255,
//second pixel r,g,b,alpha
255,0,0,255,
//etc...
};

When in Processing, you can access to r,g,b values by using red(img.pixels[i]);
Look at :

https://p5js.org/reference/#/p5.Image

Thanks!
And do you know how can I save the color pixels in a var?
Like what I am making with Processing.

You just have to say :

let img = loadImage("your_image.jpg");
let copy = img;

Yes, I understand that.

But what I’m trying to do is save all the color pixels of my image. Then I could shuffle that pixels on the screen (like the video in the post https://www.youtube.com/watch?v=Gr_sAAxdxvE).

I want that the image appears on the screen as a disarmed jigsaw puzzle.
With Processing I saved my rgb color in 3 wars, and then use it to colorize rectangles.

If I understand well, you could just shuffle the array of pixels of your source image instead of storing all the r,g,b values.