chaos/scripts/chaos.js

65 lines
1.7 KiB
JavaScript

'use strict';
import { getColor } from './utils';
/**
* 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) => {
const width = image.width;
let point = start;
if (weights === undefined) {
weights = Array.apply(null, Array(transforms.length)).map(
() => 1 / transforms.length
);
}
while (iterations--) {
const index = chooseIndex(weights);
const color = getColor(2);
// console.log(point);
// console.log(point.map(x => Math.floor(x * 10 + 100)));
point = transforms[index](point);
const i = (
Math.floor(point[1] * 50 + 50) * width +
Math.floor(point[0] * 50 + 200)
) * 4;
image.data[i] = color[0];
image.data[i + 1] = color[1];
image.data[i + 2] = color[2];
image.data[i + 3] = 255;
}
};