马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
代码:- <!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>
复制代码 结果:

|