说明:刷新页面来查看不同的随机树
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="500"></canvas>
<script>
function drawBranches(startX, startY, trunkWidth, level) {
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
if(level < 12) {
var changeX = 100 / (level + 1);
var changeY = 200 / (level + 1);
var topRightX = startX + Math.random() * changeX;
var topRightY = startY - Math.random() * changeY;
var topLeftX = startX - Math.random() * changeX;
var topLeftY = startY - Math.random() * changeY;
// draw right branch
context.beginPath();
context.moveTo(startX + trunkWidth / 4, startY);
context.quadraticCurveTo(startX + trunkWidth / 4, startY - trunkWidth, topRightX, topRightY);
context.lineWidth = trunkWidth;
context.lineCap = 'round';
context.stroke();
// draw left branch
context.beginPath();
context.moveTo(startX - trunkWidth / 4, startY);
context.quadraticCurveTo(startX - trunkWidth / 4, startY - trunkWidth, topLeftX, topLeftY);
context.lineWidth = trunkWidth;
context.lineCap = 'round';
context.stroke();
drawBranches(topRightX, topRightY, trunkWidth * 0.7, level + 1);
drawBranches(topLeftX, topLeftY, trunkWidth * 0.7, level + 1);
}
}
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
drawBranches(canvas.width / 2, canvas.height, 50, 0);
</script>
</body>
</html>