1. 程式人生 > 其它 >隨機生成的文字,在背景圖隨機排列

隨機生成的文字,在背景圖隨機排列

前言

  偶然間看到有人諮詢怎麼做隨機生成的文字,在背景圖隨機排列的思路,然後我剛好也忙完了,於是就簡單的做了一個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>

  

效果圖: