Created
April 1, 2018 01:05
-
-
Save sabha/377e1253130a509ab5a45273b70933d7 to your computer and use it in GitHub Desktop.
Triangle Fractal
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
<!DOCTYPE html> | |
<html> | |
<body> | |
<canvas id="myCanvas" width="600" height="600" | |
style="border:1px solid #d3d3d3;"> | |
Your browser does not support the canvas element. | |
</canvas> | |
<script> | |
var canvas = document.getElementById("myCanvas"); | |
var ctx = canvas.getContext("2d"); | |
var w = canvas.width; | |
var h = canvas.height; | |
var cx = w/2; | |
var cy = h/2; | |
Math.distance = function( x1, y1, x2, y2 ) { | |
var xs = x2 - x1, ys = y2 - y1; | |
xs *= xs; | |
ys *= ys; | |
return Math.sqrt( xs + ys ); | |
}; | |
var midPoint = (x1,y1,x2,y2) => ({ x: (x1 + x2)/2, y: (y1 + y2)/2 }); | |
function line(x1,y1,x2,y2){ | |
ctx.beginPath(); | |
ctx.moveTo(x1,y1); | |
ctx.lineTo(x2,y2); | |
ctx.stroke(); | |
ctx.closePath(); | |
return midPoint(x1,y1,x2,y2); | |
} | |
function circle(x,y,r){ | |
ctx.beginPath(); | |
ctx.arc(x,y,r,0,2*Math.PI); | |
ctx.stroke(); | |
ctx.closePath(); | |
} | |
function lineFrom(p1,p2){ | |
line(p1.x,p1.y,p2.x,p2.y); | |
} | |
function color() { | |
var letters = '0123456789ABCDEF'; | |
var color = '#'; | |
for (var i = 0; i < 6; i++) { | |
color += letters[Math.floor(Math.random() * 16)]; | |
} | |
return color; | |
} | |
var off = 60; | |
var l = w-(off*2); | |
var x1 = off; | |
var y1 = h-off; | |
var x2 = x1+l; | |
var y2 = y1; | |
var x3 = l*Math.cos(300*(Math.PI/180))+x1; | |
var y3 = l*Math.sin(300*(Math.PI/180))+y1; | |
var x4 = l*Math.cos(240*(Math.PI/180))+x2; | |
var y4 = l*Math.sin(240*(Math.PI/180))+y2; | |
ctx.strokeStyle = color(); | |
function tris(p1,p2,p3,f=true) { | |
if(Math.distance(p1.x,p1.y,p2.x,p2.y) >= 5) { | |
var m1 = line(p1.x,p1.y,p2.x,p2.y,f); | |
var m2 = line(p2.x,p2.y,p3.x,p3.y,f); | |
var m3 = line(p3.x,p3.y,p1.x,p1.y,f); | |
tris(m1, m2, p2); | |
tris(m2, p3, m3); | |
tris(m3, p1, m1); | |
} | |
} | |
tris({x: x1, y: y1}, | |
{x: x2, y: y2}, | |
{x: x3, y: y3}, false); | |
//circle(x1,y1,l); | |
//circle(x2,y2,l); | |
</script> | |
</body> | |
</html> |
Author
sabha
commented
Apr 1, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment