[SOLVED] Porting 'Brightness.pde' to P5.js

Porting Brightnes.pde to P5.js
Hi, I’m trying to port example of ‘Brightness’ from Processing to P5, and cannot do with success.
The similar sample found in P5 reference is that (changing some things to transform it in a similar way) :

let img;

function preload() {
  img = loadImage('proc3.jpg');
}

function setup() {
  createCanvas(460, 345);
  pixelDensity(1);
  img.loadPixels();
  loadPixels();
}

function draw() {
  for (let x = 0; x < img.width; x++) {
    for (let y = 0; y < img.height; y++) {
      // Calculate the 1D location from a 2D grid
      let loc = (x + y * img.width) * 4;
      // Get the R,G,B values from image
      let r, g, b;
      r = img.pixels[loc];
       g = green (img.pixels[loc]);
      b = blue (img.pixels[loc]);
      // Calculate an amount to change brightness based on proximity to the mouse
      let maxdist = 50;
      let d = dist(x, y, mouseX, mouseY);
      let adjustbrightness = (255 * (maxdist - d)) / maxdist;
      r += adjustbrightness;
       g += adjustbrightness;
      b += adjustbrightness;
      // Constrain RGB to make sure they are within 0-255 color range
      r = constrain(r, 0, 255);
      // Make a new color and set pixel in the window
      let c = color(r, g, b);
      let pixloc = (y * width + x) * 4;
     /* pixels[pixloc] = r;  //This code in P5 sample
      pixels[pixloc + 1] = r;
      pixels[pixloc + 2] = r;
      pixels[pixloc + 3] = 255;*/
      pixels[pixloc] = c;  // Adapted to only change the brightness, not the colors
      pixels[pixloc + 1] = c;
      pixels[pixloc + 2] = c;
      pixels[pixloc + 3] = 255;
      
    }
  }
  updatePixels();
}

But it doesn’t work. It appears a very dark image and ‘c’ doesn’t seem to work fine.
Any help?

1 Like

there are a few issues with your code. maybe it would help to look at a working example best of luck.

2 Likes

Great solution!!!
New in P5.js, I couldn’t figure out how to adapt it from Processing. Thank you, very much!!