Skip to content

Instantly share code, notes, and snippets.

@termat
Created March 13, 2019 14:23
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 termat/0aede3e098455d36f200fb237e924e74 to your computer and use it in GitHub Desktop.
Save termat/0aede3e098455d36f200fb237e924e74 to your computer and use it in GitHub Desktop.
Tree : fractal
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tree</title>
</head>
<body>
<canvas id="canvas" width="465" height="465"></canvas>
</body>
</html>
var ctx;
var graph;
var toRadian;
var step;
$(document).ready(init);
function init(){
toRadian= Math.PI/180.0;
step=0.0;
var canvas = document.getElementById('canvas');
ctx=canvas.getContext('2d');
var timer = setInterval(update, 100)
};
function update(){
ctx.clearRect(0, 0, 465, 465);
ctx.beginPath();
creatTree(ctx, 232, 465, 90, 180, 5);
creatTree(ctx, 232, 465, 45, 100, 4);
creatTree(ctx, 232, 465, 135, 100, 4);
step += (Math.PI/80.0) % Math.PI;
}
function creatTree(cx,px,py,angle,len,n){
if(n>0){
angle += 3 * Math.cos(step) - 2;
var x1 = px+0.1*len*Math.cos(angle * toRadian);
var y1 = py-0.1*len*Math.sin(angle * toRadian);
var x2 = px+len*Math.cos(angle * toRadian);
var y2 = py-len*Math.sin(angle * toRadian);
drawLine(cx,n-1,px,py,x2,y2);
var a_l = angle + 30;
var a_r = angle - 30;
len = len * 2/3;
creatTree(cx, x2, y2, angle - 3 * Math.sin(step), len, n-1);
creatTree(cx, x1, y1, a_l, len*2/3, n-1);
creatTree(cx, x1, y1, a_r, len*2/3, n-1);
creatTree(cx, x2, y2, a_l, len*2/3, n-1);
creatTree(cx, x2, y2, a_r, len*2/3, n-1);
}
};
function drawLine(cx,n,x1,y1,x2,y2){
cx.lineWidth=n;
cx.strokeStyle="rgb(0,102,0)";
ctx.beginPath();
cx.moveTo(x1,y1);
cx.lineTo(x2,y2);
ctx.stroke();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment