JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<canvas id="myCanvas" width="1500" height="800"></canvas>
</div>
CSS
canvas {
border: 1px solid white;
}
JavaScript
// redefine windows requestAnimFrame
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback,
/* DOMElement Element */
element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
var treeline = []; // tree branch
var context;
// easing function - make branch grow nature
function easeOut(t, b, c, d) {
return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
}
// add new tree branch
function addNewTreeLine(father, angle, thickness, depth) {
var length = random(0, 20);
var growtime = random(500, 1000);
var newLine = {
childs: [],
angle: angle,
thickness: thickness,
length: length,
time: 0,
depth: depth,
growtime: growtime
};
treeline.push(newLine);
if (father != null) {
father.childs.push(newLine);
}
}
// grow flower
function drawFlowers(x, y) {
context.beginPath();
context.arc(x, y, 5, Math.PI * 2, false);
context.fillStyle = 'rgb(255, 255, 0)';
context.fill();
}
// draw tree branch
function drawTree(item, x1, y1) {
if (item.depth != 0) {
var stage = easeOut(item.time, 0, 1.0, item.growtime);
var x2 = x1 + (cos(item.angle) * item.depth * item.length *
stage);
var y2 = y1 + (sin(item.angle) * item.depth * item.length *
stage);
drawLine(x1, y1, x2, y2, item.thickness * stage);
item.childs.forEach(function(child) {
drawTree(child, x2, y2);
});
} else {
drawFlowers(x1, y1);
}
}
function drawLine(x1, y1, x2, y2, thickness) {
context.fillStyle = '#000';
context.strokeStyle = 'rgb(139,126, 102)';
context.lineWidth = thickness * 1.5;
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.closePath();
context.stroke();
}
function cos(angle) {
return...