Created
November 4, 2018 05:21
-
-
Save gonzam88/64e0926a026fdb2eac760bb081621aaa to your computer and use it in GitHub Desktop.
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
var totalHeight = 500; | |
var totalWidth = 1000; | |
var W = totalWidth; | |
var H = totalHeight; | |
var maxResolution = 5; | |
var branchLength, divergence, reduction, reductionOfReduction, line_width, start_points = []; | |
function initPjs() { | |
branchLength = 50; | |
divergence = 20; | |
reduction = 0.95; | |
reductionOfReduction = 0.91; | |
var trunk = { | |
x: W / 2, | |
y: branchLength+50, | |
angle: 90 | |
}; | |
start_points.push(trunk); | |
melt.line(trunk.x, H - 50, trunk.x, H - trunk.y); | |
branches(); | |
} | |
function branches() { | |
//reducing line_width and length | |
reduction *= reductionOfReduction; | |
branchLength = branchLength * reduction; | |
line_width = line_width * reduction; | |
var new_start_points = []; | |
for (var i = 0; i < start_points.length; i++) { | |
var sp = start_points[i]; | |
//2 branches will come out of every start point. Hence there will be | |
//2 end points. There is a difference in the divergence. | |
//let rndL = RandomRange(4,10); | |
//let rndAng = RandomRange(0,70); | |
var ep1 = get_endpoint(sp.x, sp.y, sp.angle + divergence , branchLength ); | |
//rndL = RandomRange(4,20); | |
//rndAng = RandomRange(0,60); | |
var ep2 = get_endpoint(sp.x, sp.y, sp.angle - divergence , branchLength); | |
//drawing the branches now | |
//ctx.moveTo(sp.x, H-sp.y); | |
//ctx.lineTo(ep1.x, H-ep1.y); | |
//ctx.moveTo(sp.x, H-sp.y); | |
//ctx.lineTo(ep2.x, H-ep2.y); | |
melt.line(sp.x, H - sp.y,ep1.x, H - ep1.y); | |
melt.line(sp.x, H - sp.y,ep2.x, H - ep2.y); | |
//Time to make this function recursive to draw more branches | |
ep1.angle = sp.angle + divergence; | |
ep2.angle = sp.angle - divergence; | |
new_start_points.push(ep1); | |
new_start_points.push(ep2); | |
} | |
start_points = new_start_points; | |
//recursive call - only if length is more than 2. | |
//Else it will fall in an long loop | |
if (branchLength > maxResolution) branches(); | |
//else setTimeout(initPjs, 500); | |
} | |
function get_endpoint(x, y, a, myLength) { | |
//This function will calculate the end points based on simple vectors | |
var epx = x + myLength * Math.cos(a * Math.PI / 180); | |
var epy = y + myLength * Math.sin(a * Math.PI / 180); | |
return { | |
x: epx, | |
y: epy | |
}; | |
} | |
initPjs(); | |
function RandomRange(min, max){ | |
return Math.floor(Math.random() * max) + min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment