画一颗随机数

[复制链接]
发表于 2025-12-3 10:59:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
代码:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>codePen - Random Tree</title>
  6. </head>
  7. <body>
  8. <canvas></canvas>
  9. <script>
  10.     const canvas = document.querySelector('canvas');
  11.     const ctx = canvas.getContext('2d');
  12.     // canvas.width = window.innerWidth * devicePixelRatio;
  13.     // canvas.height = window.innerHeight * devicePixelRatio;
  14.     canvas.width = window.innerWidth;
  15.     canvas.height = window.innerHeight;
  16.     ctx.translate(canvas.width / 2, canvas.height);
  17.     ctx.scale(1, -1);
  18.     drawBranch([0, 0], 200, 30, 90);
  19.     function drawBranch (v0, len, thick, angle) {
  20.         if(thick < 10 && Math.random() < 0.3) {
  21.             return;
  22.         }
  23.         if (thick < 2) {
  24.             ctx.beginPath()
  25.             ctx.arc(...v0, 4, 0, 2 * Math.PI);
  26.             ctx.fillStyle = 'red';
  27.             ctx.fill();
  28.             return;
  29.         }
  30.         ctx.beginPath();
  31.         ctx.moveTo(...v0);
  32.         const v1 = [
  33.             v0[0] + len * Math.cos(((angle) * Math.PI) / 180),
  34.             v0[1] + len * Math.sin(((angle) * Math.PI) / 180)
  35.         ]
  36.         ctx.lineTo(...v1);
  37.         ctx.strokeStyle = '#333';
  38.         ctx.lineWidth = thick;
  39.         ctx.lineCap = 'round';
  40.         ctx.stroke();
  41.         drawBranch(v1, len * 0.8, thick * 0.7, angle + Math.random() * 30);
  42.         drawBranch(v1, len * 0.8, thick * 0.7, angle - Math.random() * 30);
  43.     }
  44. </script>
  45. </body>
  46. </html>
复制代码
结果:

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表