Skip to content

Instantly share code, notes, and snippets.

@GoSubRoutine
Last active February 27, 2020 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GoSubRoutine/dd290c28663ef13aaf2f1b5e8d0adffa to your computer and use it in GitHub Desktop.
Save GoSubRoutine/dd290c28663ef13aaf2f1b5e8d0adffa to your computer and use it in GitHub Desktop.
Fill Image with Random Gray
height: 300
<script async src=https://CDN.JSDelivr.net/npm/p5></script>
<script defer src=sketch.js></script>
/**
* Fill Image with Random Gray (v1.1.1)
* 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/11
*
* Bl.ocks.org/GoSubRoutine/dd290c28663ef13aaf2f1b5e8d0adffa
*/
"use strict";
const WEBCOLOR_RANGE = 0x1000, GRAY_RANGE = 0x100,
NUM_COLOR_BYTES = Int32Array.BYTES_PER_ELEMENT,
ONE_BYTE = 0o10, TWO_BYTES = 0o20, THREE_BYTES = 0o30, MAX_BYTE = 0xff;
let img;
function setup() {
createCanvas(400, 300).mousePressed(redraw);
noLoop();
img = createImage(width >> 1, height >> 1);
}
function draw() {
background(top.document.title = randomColor());
fillImgRndGray(img);
set(width - img.width >> 1, height - img.height >> 1, img);
}
function keyPressed() {
return !!redraw(); // returns false as preventDefault()
}
function randomColor() {
return '#' + hex(~~random(WEBCOLOR_RANGE), 3);
}
function fillImgRndGray(img) {
if (!img) img = createImage(width, height);
img.pixels.buffer || img.loadPixels();
const pix = new DataView(img.pixels.buffer), len = pix.byteLength;
for (let i = 0; i < len; i += NUM_COLOR_BYTES) {
const gray = ~~random(GRAY_RANGE),
RGBa = gray<<THREE_BYTES | gray<<TWO_BYTES | gray<<ONE_BYTE | MAX_BYTE;
pix.setInt32(i, RGBa);
}
img.updatePixels();
return img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment