chaos/scripts/chaos.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

2015-12-22 20:33:40 +00:00
'use strict';
import { getColor } from './utils';
2015-12-22 20:33:40 +00:00
/**
* Choose an index at random among a list of weights,
* more weighted indices have a greater proability to be chosen
2015-12-22 20:33:40 +00:00
*
* @param {Array} weights List of weights
* @return {number} Selected index
2015-12-22 20:33:40 +00:00
*/
const chooseIndex = weights => {
const number = Math.random();
let sum = 0, index = 0;
2015-12-22 20:33:40 +00:00
while (number >= sum) {
sum += weights[index];
index += 1;
2015-12-22 20:33:40 +00:00
}
return index - 1;
2015-12-22 20:33:40 +00:00
};
/**
* 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
2015-12-22 20:33:40 +00:00
*
* @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
2015-12-22 20:33:40 +00:00
* @return {null}
*/
export const applyChaos = (image, start, iterations, transforms, weights) => {
const width = image.width;
let point = start;
2015-12-22 20:33:40 +00:00
if (weights === undefined) {
weights = Array.apply(null, Array(transforms.length)).map(
() => 1 / transforms.length
);
}
2015-12-22 20:33:40 +00:00
while (iterations--) {
const index = chooseIndex(weights);
const color = getColor(2);
2015-12-22 20:33:40 +00:00
// console.log(point);
// console.log(point.map(x => Math.floor(x * 10 + 100)));
point = transforms[index](point);
2015-12-22 20:33:40 +00:00
const i = (
Math.floor(point[1] * 50 + 50) * width +
Math.floor(point[0] * 50 + 200)
) * 4;
2015-12-22 20:33:40 +00:00
image.data[i] = color[0];
image.data[i + 1] = color[1];
image.data[i + 2] = color[2];
image.data[i + 3] = 255;
2015-12-22 20:33:40 +00:00
}
};