Pixels array p5.js vs java improving speed

If your aim was just to make it run online just know your sketch is totally convertible to Processing.js:

index.html:

<script defer src=https://Unpkg.com/processing-js></script>
<canvas data-src=Trig_Pixel_Colors.pde></canvas>

As you can see from the embedded <iframe> above I’ve made many changes to your Java sketch.

Most important 1 was moving the K[] array initialization to setup().

After all, nothing in the K[] array changes after it’s filled w/ colors the 1st time, just like A[].

While Java Mode uses a 32bit integer value to represent an aRGB color for its pixels[] array, p5js version goes w/ an Uint8ClampedArray container which requires 4 elements to represent an RGBa value:

However there’s a workaround to access p5js’ pixels[] as a 32bit value!

We simply create a new 32bit typed array, either Int32Array or Uint32Array, and pass the pixels[]'s Uint8ClampedArray::buffer to its constructor:
pix32 = new Uint32Array(pixels.buffer);

This way we get a view over the original Uint8ClampedArray container, where any changes made to 1 reflect on the other.

The only trap about it is that typed arrays store their values according to a computer’s endianness, which for almost all personal devices is little-endian:

So we need to invert the byte-order when we’re converting a sequence of RGBa 8bit values to a 32bit unified value, resulting in an aBGR order!

Another obstacle is that p5js’ color() returns a p5.Color object rather than a 32bit value like Processing’s.

Among the many p5.Color undocumented properties is levels[], which stores an RGBa representation as a 4-length array:
{ levels: rgbaArray } = color(R + u, G + v, B + u),

The line above relies on an object destructuring assignment in order to unpack the levels[] property from the p5.Color object and then rename it to rgbaArray[].

Next step now is to convert that 4-length array to an aBGR unified value.

For that I’ve chosen method Array::reduce():

abgrValue = rgbaArray.reduce(RGBa_Arr_to_aBGR_32bit_Val, 0);

function RGBa_Arr_to_aBGR_32bit_Val(acc, val, idx) {
  return acc | val << idx * 0o10;
}

Here’s the complete p5js sketch running online w/ same performance as Processing’s:

index.html:

<script async src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=sketch.js></script>

Extra links about other JS syntaxes I’ve used on the p5js flavor:

3 Likes