🦌

Image distortion in p5js

type
article
tags
just4fun
tl;dr
Speedy per-pixel transformation in p5js
date
Aug 9, 2020
I recently started exploring p5js to up my math game a little and practice per-pixel manipulation. I picked p5js because I like the interactivity and real-time feedback, it has an easy syntax and it's easy to test the code in either the web-editor or with the processing app (using the p5js plugin).
After some fiddling around the "finished product" can distort any image using noise and the mouse position:
Transform with MousePos
Transform with MousePos
Transform with MousePos*noise
Transform with MousePos*noise
 
In the process I realized that it might not be the best solution for advanced image manipulation because it gets slow - even with small images. So I spent a large portion of the time on performance optimization which involved writing replacements for the built in get and set functions:
function fget(x, y, src=pixels) {
  x = parseInt(x);
  y = parseInt(y);
  let off = ((y * width) + (x)) * pxd * 4;
  return [
    src[off],
    src[off + 1],
    src[off + 2],
    src[off + 3]
  ];
}

function fset(x, y, col, src=pixels) {
  x = parseInt(x);
  y = parseInt(y);
  let off = ((y * width) + (x)) * pxd * 4;
  src[off] = col[0];
  src[off + 1] = col[1];
  src[off + 2] = col[2];
  src[off + 3] = col[3];
}
If you feel like playing around with it you can find the p5.js source here.