chaos/scripts/index.js

97 lines
2.2 KiB
JavaScript
Raw Normal View History

'use strict';
2015-12-21 22:37:34 +00:00
import { html } from 'the-dom';
2015-12-22 20:33:40 +00:00
import { getColor } from './utils';
import { createRegularVertices, scaleVertices, applyChaos } from './chaos';
const { body } = html(document);
2015-12-21 22:37:34 +00:00
const content = body.find('#content');
2015-12-22 20:33:40 +00:00
const verticesRange = body.find('#vertices');
const fractionRange = body.find('#fraction');
const plotting = body.find('#plotting').node;
const ctx = plotting.getContext('2d');
const padding = 40; // padding between the canvas edges and the points
2015-12-22 20:33:40 +00:00
let width, height, vertices;
/**
2015-12-22 20:33:40 +00:00
* Re-render the scene from scratch
*
2015-12-22 20:33:40 +00:00
* @return {null}
*/
2015-12-22 20:33:40 +00:00
const render = () => {
const fraction = 1 / parseFloat(fractionRange.node.value);
const scaledVerts = scaleVertices(width, height, vertices);
plotting.width = width + 2 * padding;
plotting.height = height + 2 * padding;
2015-12-22 20:33:40 +00:00
// do not plot (very) small sizes
if (width < 1) {
return;
}
2015-12-22 20:33:40 +00:00
// draw the polygon
ctx.strokeStyle = '#aaa';
ctx.lineWidth = 1;
2015-12-22 20:33:40 +00:00
ctx.beginPath();
2015-12-22 20:33:40 +00:00
for (let i = 0; i < vertices.length; i += 1) {
ctx.lineTo(scaledVerts[i][0] + padding, scaledVerts[i][1] + padding);
}
2015-12-22 20:33:40 +00:00
ctx.closePath();
ctx.stroke();
2015-12-22 20:33:40 +00:00
// draw the vertices
for (let i = 0; i < vertices.length; i += 1) {
ctx.beginPath();
ctx.fillStyle = 'rgb(' + getColor(i).join(', ') + ')';
ctx.arc(
scaledVerts[i][0] + padding, scaledVerts[i][1] + padding,
4, 0, Math.PI * 2
);
2015-12-22 20:33:40 +00:00
ctx.fill();
}
2015-12-22 20:33:40 +00:00
// do the chaos game
const image = ctx.getImageData(padding, padding, width, height);
applyChaos(image, fraction, scaledVerts);
ctx.putImageData(image, padding, padding);
};
/**
2015-12-22 20:33:40 +00:00
* Update the scene when the window has been resized
*
* @return {null}
*/
const resize = () => {
2015-12-22 20:33:40 +00:00
width = content.node.clientWidth - 2 * padding;
height = content.node.clientHeight - 2 * padding;
render();
};
2015-12-22 20:33:40 +00:00
/**
* Create new vertices
*/
verticesRange.on('input', () => {
vertices = createRegularVertices(
parseInt(verticesRange.node.value, 10)
);
render();
});
window.onresize = resize;
2015-12-22 20:33:40 +00:00
fractionRange.on('input', render);
vertices = createRegularVertices(3);
resize();