Skip to content

Instantly share code, notes, and snippets.

@curran
Last active December 8, 2015 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/753a89ecc73b07cdcf66 to your computer and use it in GitHub Desktop.
Save curran/753a89ecc73b07cdcf66 to your computer and use it in GitHub Desktop.
Tree Fractal with Circles
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--
An interactive fractal experiment using HTML5 Canvas
Curran Kelleher 10/28/2014
-->
<title>fractal</title>
</head>
<body>
<canvas id="fractal" width="960" height="500"></canvas>
<script>
var canvas = document.getElementById("fractal"),
ctx = canvas.getContext("2d"),
nMax = 95,
mouseX = 800, mouseY = 83
scaleFactor = (100 - 4.4688) / 100;
function redraw (){
var scale = 20,
angle = -mouseY / canvas.height * Math.PI / 8;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var n = Math.floor(nMax * mouseX / 960);
ctx.save();
ctx.translate(497, 472);
drawGeometry(scale, angle, 0, n, false);
ctx.restore();
}
// The recursive fractal definition
function drawGeometry(scale, angle, i, n, flip){
drawCircle(0, 0, scale / 2)
ctx.translate(0, -scale);
ctx.rotate(flip ? angle : -angle);
if(i < n){
ctx.save();
// Continue the current branch.
drawGeometry(scale * scaleFactor, angle, i+1, n, flip);
// Create a new branch every 10 circles.
if(i % 11 === 0){
drawGeometry(scale * scaleFactor, angle, i+1, n, !flip);
}
ctx.restore();
}
}
function drawCircle(x, y, radius){
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.fill();
}
redraw();
canvas.addEventListener("mousemove",function(e){
mouseX = e.x;
mouseY = e.y;
redraw();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment