50 lines
1.3 KiB
JavaScript
50 lines
1.3 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Choose an index at random among a list of weights,
|
|
* more weighted indices have a greater proability to be chosen
|
|
*
|
|
* @param {Array} weights List of weights
|
|
* @return {number} Selected index
|
|
*/
|
|
const chooseIndex = weights => {
|
|
const number = Math.random();
|
|
let sum = 0, index = 0;
|
|
|
|
while (number >= sum) {
|
|
sum += weights[index];
|
|
index += 1;
|
|
}
|
|
|
|
return index - 1;
|
|
};
|
|
|
|
/**
|
|
* Apply the chaos game: starting from `start`, we plot
|
|
* the next `n` points. To get to the next point, we apply
|
|
* a random transformation among given ones
|
|
*
|
|
* @param {ImageData} image Image to write on
|
|
* @param {Array} start Starting point
|
|
* @param {number} iterations Number of points to plot
|
|
* @param {Array} transforms List of available transforms
|
|
* @param {Array} weights Probability weights for each transform
|
|
* @return {null}
|
|
*/
|
|
export const applyChaos = (image, start, iterations, transforms, weights, cb) => {
|
|
let point = start;
|
|
|
|
if (weights === undefined) {
|
|
weights = Array.apply(null, Array(transforms.length)).map(
|
|
() => 1 / transforms.length
|
|
);
|
|
}
|
|
|
|
while (iterations--) {
|
|
const index = chooseIndex(weights);
|
|
point = transforms[index](point);
|
|
|
|
cb(point);
|
|
}
|
|
};
|