P5.js : manually calculate additive blendmode with pixels[]

Viewed 249

I’m currently coding a P5.js program in which I draw some random generated patterns like this :

function setup() {
     colorMode(RGB, 255, 255, 255, 255);
     blendMode(ADD);
}

function draw() {
    for(var i = 0; i < 20000; i++)
    {
      x = generateCoordinatesX();
      y = generateCoordinateY();

      var pointColor = generateColor(); //rgba

      stroke(pointColor);
      point(x, y);
     }
}

When two ore more points get supperposed, they are displayed with additive BlendMode. As the number of point is quite big, it slows down the simulation a lot. I tried to adapt this code with the pixels method like bellow to speed up things :

function draw() {
    loadPixels();
    for(var i = 0; i < 20000; i++)
    {
      x = generateCoordinatesX();
      y = generateCoordinateY();
      var index = (x + y * width)*4;
      
      pixels[index+0] += ???;
      pixels[index+1] += ???;
      pixels[index+2] += ???;
      pixels[index+3] += ???;
     }
     updatePixels();
}

The issue is that i dont know how to generate the R,G,B,A value so that it behave with additive Blending like my first version. Is there a way to manually calculate this ? I tried with formulas i found but after some tests, the results are different.

Thanks in advance

1 Answers

There's a bunch of very helpful methods that will fill in this information for you. They are respectively named red, green, blue and alpha, and you can use them to extract the relevant information from a known color.

Here's a code snippet to demonstrate:

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

 background(color(0, 255, 0));
}

function draw() {
}

function mouseClicked() {
  let blendColor = color(128,0,0);
  let density = pixelDensity();
  
  loadPixels();
  for (var i=0; i<width*height*density*4; i+=4)
  {
    pixels[i] += red(blendColor);
    pixels[i+1] += green(blendColor);
    pixels[i+2] += blue(blendColor);
    pixels[i+3] += alpha(blendColor);
  }
  updatePixels();
}

Once you click on the canvas, it'll update the background color by adding the blendColor to the pixel array. I deliberately choose a color that you can blend more than once to demonstrate that there won't be any stack overflow if you try to blend two colors which should go over 8-bit (255) in intensity, so you can click more than once without fearing a crash.

Hope it helps. Have fun!

Related