Skip to content

Instantly share code, notes, and snippets.

@sabha
Created April 1, 2018 04:18
Show Gist options
  • Save sabha/ad37db53d7fcfb92523949cfcb6c4866 to your computer and use it in GitHub Desktop.
Save sabha/ad37db53d7fcfb92523949cfcb6c4866 to your computer and use it in GitHub Desktop.
Line Fractal
<!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 mx = 0;
var my = 0;
var off = 140;
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);*/
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
mx = evt.clientX - rect.left;
my = evt.clientY - rect.top;
mx = mx.toFixed(5);
my = my.toFixed(5);
}
canvas.addEventListener('mousemove', getMousePos, false);
function star(p,len){
if(len > 10) {
for(var i = 0; i<8;i++){
var x2 = len*Math.cos((45*i)*(Math.PI/180))+(p.x);
var y2 = len*Math.sin((45*i)*(Math.PI/180))+(p.y);
var m = midPoint(p.x,p.y,x2,y2);
ctx.beginPath();
ctx.moveTo(p.x,p.y);
ctx.bezierCurveTo(m.x,m.y,m.x-30,m.y+30,x2,y2);
/*for(var x = p.x; x<=p.x+len;x+=4) {
var y = 40*Math.sin(x*(Math.PI/180));
ctx.lineTo(x,y);
}*/
ctx.stroke();
ctx.closePath();
line(p.x,p.y,x2,y2)
star({x: x2,y: y2}, len/2);
}
}
}
//setInterval(()=>{
//ctx.clearRect(0,0,w,h);
star({x:cx,y:cy},150);
//},150)
//circle(x1,y1,l);
//circle(x2,y2,l);
</script>
</body>
</html>
@sabha
Copy link
Author

sabha commented Apr 1, 2018

screen shot 2018-03-31 at 11 18 46 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment