JSFiddle - React, Tailwind, and code Playground
by nchaves
HTML
<button onclick="generateRandomness(this);">Generate</button><br/>
<button onclick="generateRandomness(this, mwc.rand);">Generate mwc</button><br/>
<button onclick="generateRandomness(this, mwc.rand, RandomMode.ALPHA);">Generate mwc alpha</button><br/>
<button onclick="generateRandomness(this, mwc.rand, RandomMode.FULL_COLOR);">Generate mwc color</button><br/>
<canvas id="c" width="400" height="400"></canvas>
JavaScript
// Complementary Multiply-With-Carry of lag 1
// similar to Chrome's implementation (structured more traditionally)
var mwc = (function() {
// Set two seed values.
var carry, x,
// Value of modulus and multiplier are chosen together
// 2^32 is chosen because it's similar to the others
// but we don't use bitwise operations to take advantage of this
max = Math.pow(2, 32),
a = 3636507990;
return {
setSeed : function(arr) {
var seed = arr || [0,1].map(function() {
return Math.round(Math.random() * max);
});
carry = seed[0];
x = seed[1];
},
getSeed : function() {
return [carry, x];
},
rand : function() {
// Two multiplications
// create carry with division, x with mod
// The first part is the "carry" where we're
// using both parts of the residue
carry = ((a * x) + carry) / max;
// subtracting from the max is what makes it the compliment
x = (max - 1) - ((a * x) + carry) % max;
return x / max;
}
};
}());
mwc.setSeed();
var RandomMode = {
BINARY: 1,
ALPHA: 2,
FULL_COLOR: 3
};
var generateRandomness = function (btn, randomFn, mode) {
randomFn = randomFn || Math.random;
mode = mode || RandomMode.BINARY;
var c = document.getElementById('c');
var ctx = c.getContext('2d');
ctx.clearRect(0, 0, 400, 400);
var idata = ctx.createImageData(1, 1);
var d = idata.data;
for (var x = 0; x < 400; x++) {
for (var y = 0; y < 400; y++) {
switch (mode) {
case RandomMode.BINARY:
d[3] = 0xff; // alpha
if (Math.random() >= 0.5) {
d[0] = d[1] = d[2] = 0;
} else {
d[0] = d[1] = d[2] = 0xff;
}
break;
case RandomMode.ALPHA:
d[0] = d[1] = d[2] = 0;
d[3] = Math.round(randomFn() * 0xff);
break;
case RandomMode.FULL_COLOR:
d[0] = Math.round(randomFn() * 0xff);
d[1] =...