P5 JS random/shuffle pixels


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:

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() {
  img = loadImage("san.jpg");

void draw() {
  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]);
      rect (x,y,1,1);

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

var img;

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

function setup() {
  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]);
      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?

P.S: Sorry for my english :slight_smile:


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

img.pixels = {
//first pixel r,g,b,alpha
//second pixel r,g,b,alpha

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


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.