前言

  偶然间看到有人咨询怎么做随机生成的文字,在背景图随机排列的思路,然后我刚好也忙完了,于是就简单的做了一个dom,给需要的人参考下。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>随机文字排列</title>
  <style>
    .body {
      width: 100vw;
      height: 100vh;
      position: fixed;
    }
  </style>
</head>
<body>
  <section class="body"></section>
</body>
<script>
  const randomNum = num => {
    return parseInt(Math.random()*num);
  }
  
  // 随机生成的文字,在背景图随机排列
  const randomText = () => {
    let _rsl = "";
    let _randomUniCode = Math.floor(Math.random() * (40870 - 19968) + 19968).toString(16);
    eval("_rsl=" + '"\\u' + _randomUniCode + '"');//eval()可以接受一个字符串str作为参数,并把这个参数作为脚本代码来执行
    return _rsl;
  }

  // 随机颜色
  const randomColor = () => {
    const r = randomNum(255);
    const g = randomNum(255);
    const b = randomNum(255);
    const a = parseFloat(Math.random().toFixed(1) + 0.1);
    return `rgba(${r}, ${g}, ${b}, ${a})`;
  }

  // 随机位置--也可以自己或者指定的dom元素高宽
  const randomLocation = (width,height) => {
    let x = randomNum(width);
    let y = randomNum(height);
    return {x, y}
  }

  // 随机角度
  const randomAngle = (rotate=360) => {
    return `rotate(${randomNum(rotate)}deg)`;
  }

  // 随机大小
  const randomSize = (size=30) => {
    return `${randomNum(size)}px`;
  }

  let dom = document.getElementsByClassName('body')[0];
  let x ,y = '';
  for(let i=0; i<100; i++) {
    x = randomLocation(dom.clientWidth, dom.clientHeight).x;
    y = randomLocation(dom.clientWidth, dom.clientHeight).y;
    dom.innerHTML += `<span style="color: ${randomColor()};position: fixed;top: ${y}px;left: ${x}px;transform: ${randomAngle()};font-size: ${randomSize()};">${randomText()}</span>`;
  };
</script>
</html>

  

效果图:

 

posted on 2022-12-09 14:18  Tom最好的朋友是Jerry  阅读(164)  评论(0编辑  收藏  举报