代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>codePen - Random Tree</title>
</head>
<body>
<canvas></canvas>
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// canvas.width = window.innerWidth * devicePixelRatio;
// canvas.height = window.innerHeight * devicePixelRatio;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.translate(canvas.width / 2, canvas.height);
ctx.scale(1, -1);
drawBranch([0, 0], 200, 30, 90);
function drawBranch (v0, len, thick, angle) {
if(thick < 10 && Math.random() < 0.3) {
return;
}
if (thick < 2) {
ctx.beginPath()
ctx.arc(...v0, 4, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
return;
}
ctx.beginPath();
ctx.moveTo(...v0);
const v1 = [
v0[0] + len * Math.cos(((angle) * Math.PI) / 180),
v0[1] + len * Math.sin(((angle) * Math.PI) / 180)
]
ctx.lineTo(...v1);
ctx.strokeStyle = '#333';
ctx.lineWidth = thick;
ctx.lineCap = 'round';
ctx.stroke();
drawBranch(v1, len * 0.8, thick * 0.7, angle + Math.random() * 30);
drawBranch(v1, len * 0.8, thick * 0.7, angle - Math.random() * 30);
}
</script>
</body>
</html>
效果: