Pushing a 7712x960 Binary image to p5.js is Super slow. Is there a better way?

Made my own version using a DataView + its method setInt32() as a wrapper to write to pixels[] 4 bytes (RGBa) at once: :grinning:


Dunno whether it’s faster or not, but you can check it out online here: :clown_face:

/**
 * Fill Image with Random Gray (v1.0.3)
 * GoToLoop (2018-May-26)
 *
 * https://Discourse.Processing.org/t/
 * pushing-a-7712x960-binary-image-to-p5-js-
 * is-super-slow-is-there-a-better-way/371/8
 *
 * Bl.ocks.org/GoSubRoutine/dd290c28663ef13aaf2f1b5e8d0adffa
 */

"use strict";

let img;

function setup() {
  createCanvas(400, 300).mousePressed(redraw);
  noLoop();
  img = createImage(width >> 1, height >> 1);
}

function draw() {
  background(top.document.title = '#' + hex(~~random(0x1000), 3));
  fillImgRndGray(img);
  set(width - img.width >> 1, height - img.height >> 1, img);
}

function keyPressed() {
  return !!redraw();
}

function fillImgRndGray(img) {
  if (!img)  img = createImage(width, height);
  img.pixels.buffer || img.loadPixels();

  const pix = new DataView(img.pixels.buffer),
        len = pix.byteLength,
        bytes = Int32Array.BYTES_PER_ELEMENT,
        range = 0x100;

  for (let i = 0; i < len; i += bytes) {
    const gray = ~~random(range),
          RGBa = gray<<0o30 | gray<<0o20 | gray<<0o10 | 0xff;

    pix.setInt32(i, RGBa);
  }

  img.updatePixels();
  return img;
}
1 Like