Last active
August 22, 2020 16:48
-
-
Save ly0va/cf80bcd498c4dfda579210cfd0c7a44a to your computer and use it in GitHub Desktop.
Random fractal tree that is seeded from your name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="https://unpkg.com/p5"></script> | |
<script language="javascript" type="text/javascript" src="nice_tree.js"></script> | |
<style> | |
body { | |
padding: 0; | |
margin: 0; | |
} | |
</style> | |
</head> | |
<body> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const trunkLength = 200; | |
const trunkThikness = 20; | |
const leaf = 6; | |
const wantToSeed = true; | |
let angle, wantRandom; | |
function tree(len) { | |
if (len <= leaf / 2) { | |
noStroke(); | |
ellipse(0, 0, | |
random(leaf, leaf * 2), | |
random(leaf, leaf * 2)); | |
return; | |
} | |
let thick = map(len, 0, trunkLength, 0, trunkThikness); | |
strokeWeight(thick); | |
line(0, 0, 0, len); | |
translate(0, len); | |
for (let sign of [1, -1]) { | |
push(); | |
if (wantRandom.checked()) { | |
rotate(sign * random(PI / 12, PI / 3)); | |
tree(len * random(0.5, 0.8)); | |
} else { | |
rotate(sign * angle.value()); | |
tree(len * 0.7); | |
} | |
pop(); | |
} | |
} | |
function change() { | |
if (wantRandom.checked()) { | |
angle.hide(); | |
} else { | |
angle.show(); | |
} | |
redraw(); | |
} | |
function keyPressed() { | |
if (keyCode == ENTER && wantRandom.checked()) { | |
redraw(); | |
} | |
} | |
function setup() { | |
createCanvas(windowWidth, windowHeight); | |
colorMode(HSB); | |
stroke(0, 100, 50, 0.7); | |
fill(120, 100, 80, 0.3); | |
wantRandom = createCheckbox('Random?', true); | |
wantRandom.position(0, 0); | |
wantRandom.changed(change); | |
angle = createSlider(PI / 18, 2 * PI / 5, PI / 4, PI / 180); | |
angle.position(0, 20); | |
angle.input(redraw); | |
angle.hide(); | |
noLoop(); | |
if (wantToSeed) { | |
let seed = prompt('Enter your name'); | |
randomSeed(hash(seed.toLowerCase())); | |
} | |
} | |
function draw() { | |
background(200, 20, 100); | |
translate(width / 2, height); | |
rotate(PI); | |
tree(trunkLength); | |
} | |
function hash(str) { | |
const prime = 37; | |
const mod = 1000 * 1000 * 1000 + 7; | |
let res = 0, power = 1; | |
for (let i = 0; i < str.length; i++) { | |
res = (res + str.charCodeAt(i) * power) % mod; | |
power = power * prime % mod; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment