Skip to content

Instantly share code, notes, and snippets.

@sabha
Last active March 29, 2018 15:57
Show Gist options
  • Select an option

  • Save sabha/25b0c326e3ac1bdc436712e19e00d68b to your computer and use it in GitHub Desktop.

Select an option

Save sabha/25b0c326e3ac1bdc436712e19e00d68b to your computer and use it in GitHub Desktop.
Fractal
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1000" height="800" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</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;
var mx = 0;
var my = 0;
Math.distance = function( x1, y1, x2, y2 ) {
var xs = x2 - x1, ys = y2 - y1;
xs *= xs;
ys *= ys;
return Math.sqrt( xs + ys );
};
function circle(x,y, r = 1, fill = false){
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
}
function line(x,y, dx, dy) {
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(dx,dy);
ctx.stroke();
ctx.closePath();
}
function color() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function midPoint(x1,y1,x2,y2){
return { x: (x1+x2)/2, y: (y1+y2)/2 }
}
function writeMessage(message) {
ctx.beginPath();
ctx.font = '18pt Calibri';
ctx.fillStyle = 'black';
ctx.fillText(message, 10, 25);
ctx.closePath();
}
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);
var factorial = function(number, data) {
if (number > 0) { // terminal case
var { x1, y1 , x2, y2, angle, direction } = data;
ctx.lineWidth = number/2;
line(x1,y1,x2,y2);
var length = Math.distance(x1, y1 , x2, y2);
var len = length/4;
var dataNew = {
x1: x2,
y1: y2,
x2: (length-len)*Math.cos(angle*(Math.PI/180))+x2,
y2: (length-len)*Math.sin(angle*(Math.PI/180))+y2,
angle: angle + off,
}
factorial(number - 1, dataNew);
dataNew = {
x1: x2,
y1: y2,
x2: (length-len)*Math.cos(angle*(Math.PI/180))+x2,
y2: (length-len)*Math.sin(angle*(Math.PI/180))+y2,
angle: angle - off,
}
factorial(number - 1, dataNew);
}
};
var off = my/5;
var count = 11;
var stemHeight = 200;
ctx.strokeStyle = color();
setInterval(()=>{
ctx.clearRect(0,0,w,h);
off = my/5;
ctx.lineWidth=2;
factorial(count, {x1: cx, y1: h - 10, x2: cx, y2: cy+stemHeight , angle: 270+off });
factorial(count, {x1: cx, y1: h - 10, x2: cx, y2: cy+stemHeight , angle: 270-off });
}, 100)
</script>
</body>
</html>
@sabha

sabha commented Mar 29, 2018

Copy link
Copy Markdown
Author

screen shot 2018-03-29 at 10 56 19 am

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