Skip to content

Instantly share code, notes, and snippets.

@etra0
Created January 6, 2019 04:53
Show Gist options
  • Save etra0/8df16e7553ab543bec0324b44b083408 to your computer and use it in GitHub Desktop.
Save etra0/8df16e7553ab543bec0324b44b083408 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Random Sierpinsky</title>
</head>
<body>
</body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js'></script>
<script>
'use strict';
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var WIDTH = 400,
HEIGHT = 400;
var NPOINTS = 1;
var tri = [
[0, -.366-.25],
[-.5, .5-.25],
[.5, .5-.25]];
var randomPoints = [];
var slider;
var button;
var npoints_elements;
function setup() {
slider = createSlider(1, 100, 1);
createCanvas(WIDTH, HEIGHT);
for (let i = 0; i < 100; i++) {
randomPoints.push([0, 0])
}
button = createButton('Limpiar');
button.mousePressed(clean);
npoints_elements = createElement("p", 'Cantidad de puntos: ' + NPOINTS);
}
function clean() {
background(255);
}
function draw() {
NPOINTS = slider.value();
npoints_elements.html(`Cantidad de puntos: ${NPOINTS}`);
translate(WIDTH/2, HEIGHT/2);
scale(WIDTH/2, HEIGHT/2);
noStroke()
for (let i = 0; i < NPOINTS; i++) {
fill(0, 255*i/NPOINTS, 150 + 105*i/NPOINTS);
ellipse(...randomPoints[i], 0.01);
let randomVector = getVector(getRandomInt(1, 6), randomPoints[i]);
randomPoints[i][0] += randomVector[0];
randomPoints[i][1] += randomVector[1];
}
}
function calculateDistance(a, b) {
let _a = a[0]-b[0];
let _b = a[1]-b[1];
return [_a/2, _b/2];
}
function getVector(randomValue, currentPosition) {
if ((randomValue == 3) || (randomValue == 6)) {
return calculateDistance(tri[0], currentPosition)
} else if ((randomValue == 2) || (randomValue == 5)) {
return calculateDistance(tri[2], currentPosition)
} else {
return calculateDistance(tri[1], currentPosition)
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment