Last active
February 27, 2020 11:43
-
-
Save GoSubRoutine/dd290c28663ef13aaf2f1b5e8d0adffa to your computer and use it in GitHub Desktop.
Fill Image with Random Gray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 300 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script async src=https://CDN.JSDelivr.net/npm/p5></script> | |
<script defer src=sketch.js></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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