【问题标题】:Optimize generation of random colours优化随机颜色的生成
【发布时间】:2021-05-23 05:42:44
【问题描述】:

我刚刚开始使用 Javascript,并且我做了我的第一个小项目,所以如果代码不好并且伤害了您的眼睛,我深表歉意。

我制作了一个调色板生成器,它创建随机的十六进制颜色代码循环遍历数组。

我想知道是否有更好的方法来做到这一点,也许只使用一个循环并同时获得三个不同的十六进制代码?

//declare variables to store color codes visible on dom
const hexCode01 = document.querySelector('.hex-color-code-01');
const hexCode02 = document.querySelector('.hex-color-code-02');
const hexCode03 = document.querySelector('.hex-color-code-03');

//declare variables to store color each box
const box01 = document.querySelector('.box-01');
const box02 = document.querySelector('.box-02');
const box03 = document.querySelector('.box-03');

//declare variables to store action button
const changeBtn = document.querySelector('.change-button');

//declare array to store hex digits
const hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];

changeBtn.addEventListener("click", () => {
  //change button content after first click
  if (changeBtn.innerHTML === 'Generate Palette') changeBtn.innerHTML = 'Generate New Palette';
  else {
    changeBtn.innerHTML = 'Generate New Palette';
  }
  let activeHex1 = "#";
  let activeHex2 = "#";
  let activeHex3 = "#";

  //generate first color
  for (let i = 0; i < 6; i++) {
    const indexBox1 = Math.floor(Math.random() * hexValues.length);
    activeHex1 += hexValues[indexBox1];
  }

  //generate second color
  for (let i = 0; i < 6; i++) {
    const indexBox2 = Math.floor(Math.random() * hexValues.length);
    activeHex2 += hexValues[indexBox2];
  }

  //generate thitd color
  for (let i = 0; i < 6; i++) {
    const indexBox3 = Math.floor(Math.random() * hexValues.length);
    activeHex3 += hexValues[indexBox3];

  }

  let bodyColor1 = (hexCode01.innerHTML = activeHex1);
  let bodyColor2 = (hexCode02.innerHTML = activeHex2);
  let bodyColor3 = (hexCode03.innerHTML = activeHex3);

  box01.style.backgroundColor = bodyColor1;
  box02.style.backgroundColor = bodyColor2;
  box03.style.backgroundColor = bodyColor3;
});
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  height: 100vh;
  width: 100vw;
  font-family: arial, sans-serif;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.color-box {
  width: 33.333%;
  height: 100%;
  border: 1px solid black;
  text-transform: uppercase;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ffffff;
}

button {
  background: none;
  border: 2px solid #000;
  bottom: 1rem;
  border-radius: 50px;
  padding: 1rem;
  position: fixed;
  font-family: arial, sans-serif;
  font-size: 0.8rem;
  text-transform: uppercase;
  color: #000;
  cursor: pointer;
}

button:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

button:active {
  color: #fdfdfd;
  border-color: #fdfdfd;
}
<div class="color-box box-01">
  <div class="hex-color-code-01">#ffffff</div>
</div>
<div class="color-box box-02">
  <div class="hex-color-code-02">#ffffff</div>
</div>
<div class="color-box box-03">
  <div class="hex-color-code-03">#ffffff</div>
</div>
<button class="change-button">Generate Palette</button>

谢谢

【问题讨论】:

标签: javascript arrays for-loop math


【解决方案1】:

我省略了大部分样式和装饰,专注于 JavaScript 十六进制生成优化:

function generate() {
  var colorBoxes = document.getElementsByClassName("color-box");
  for (var i = 0; i < colorBoxes.length; i++) colorBoxes[i].innerHTML = colorBoxes[i].style.background = "#" + ("00000" + Math.floor(Math.random() * 16777216).toString(16)).slice(-6);
}
.color-box {
  display: inline-block;
  padding: 20px;
  margin-top: 20px;
}
<div><button onclick="generate();">Generate Palette</button></div>
<div class="color-box"></div>
<div class="color-box"></div>
<div class="color-box"></div>

如果您希望颜色生成更随机,可以使用rando.js 代替,如下所示:

console.log("#" + ("00000" + rando(16777215).toString(16)).slice(-6));
&lt;script src="http://randojs.com/2.0.0.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    您不需要hexValues 数组。

    十六进制的0FFFFFF 是十进制的016777215。您可以在这两个限制之间(并包括)选择一个随机数并转换为十六进制,确保在左侧填充0s。我们需要在函数中使用16777215 + 1 = 16777216 来确保16777215 是潜在的输出:

    function randomColour() {
      var randInt = Math.floor(Math.random() * 16777216); // random between 0 and 16777215
      var randHex = randInt.toString(16); // convert to hexadecimal
      var randColour = "#" + randHex.padStart(6, "0"); // pad left with 0s if hex is less than 6 chars
      return randColour; // return the random hex value
    }
    
    console.log(randomColour());

    要同时返回 3 个(或任意数量的)十六进制值颜色,请使用数组映射:

    function randomColour() {
      var randInt = Math.floor(Math.random() * 16777216);
      var randHex = randInt.toString(16);
      var randColour = "#" + randHex.padStart(6, "0");
      return randColour;
    }
    
    var numColours = 3; // your code has 3 random colours, adjust this for N colours
    var colours = Array.from({length: numColours}, function(v) {return randomColour();});
    
    console.log(colours);

    这是一种更简洁的方式来处理您在问题中提到的内容:

    ...也许只使用一个循环并获得三个不同的十六进制代码 同一时间?

    和这样做是一样的,只不过是一行:

    function randomColour() {
      var randInt = Math.floor(Math.random() * 16777216);
      var randHex = randInt.toString(16);
      var randColour = "#" + randHex.padStart(6, "0");
      return randColour;
    }
    
    var colours = [];
    var numColours = 3;
    for (var i=0; i<numColours; i++) {
      colours.push(randomColour());
    }
    
    console.log(colours);

    在您的代码中应用这种方法:

    //declare variables to store color codes visible on dom
    const hexCode01 = document.querySelector('.hex-color-code-01');
    const hexCode02 = document.querySelector('.hex-color-code-02');
    const hexCode03 = document.querySelector('.hex-color-code-03');
    
    //declare variables to store color each box
    const box01 = document.querySelector('.box-01');
    const box02 = document.querySelector('.box-02');
    const box03 = document.querySelector('.box-03');
    
    //declare variables to store action button
    const changeBtn = document.querySelector('.change-button');
    
    changeBtn.addEventListener("click", () => {
      //change button content after first click
      if (changeBtn.innerHTML === 'Generate Palette') changeBtn.innerHTML = 'Generate New Palette';
      else {
        changeBtn.innerHTML = 'Generate New Palette';
      }
    
      var colours = Array.from({length: 3}, function(v) {return randomColour();});
      
      let bodyColor1 = (hexCode01.innerHTML = colours[0]);
      let bodyColor2 = (hexCode02.innerHTML = colours[1]);
      let bodyColor3 = (hexCode03.innerHTML = colours[2]);
      
      box01.style.backgroundColor = colours[0];
      box02.style.backgroundColor = colours[1];
      box03.style.backgroundColor = colours[2];
    });
    
    function randomColour() {
      var randInt = Math.floor(Math.random() * 16777216);
      var randHex = randInt.toString(16);
      var randColour = "#" + randHex.padStart(6, "0");
      return randColour;
    }
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      height: 100vh;
      width: 100vw;
      font-family: arial, sans-serif;
      font-size: 1rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .color-box {
      width: 33.333%;
      height: 100%;
      border: 1px solid black;
      text-transform: uppercase;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #ffffff;
    }
    
    button {
      background: none;
      border: 2px solid #000;
      bottom: 1rem;
      border-radius: 50px;
      padding: 1rem;
      position: fixed;
      font-family: arial, sans-serif;
      font-size: 0.8rem;
      text-transform: uppercase;
      color: #000;
      cursor: pointer;
    }
    
    button:hover {
      background-color: rgba(255, 255, 255, 0.3);
    }
    
    button:active {
      color: #fdfdfd;
      border-color: #fdfdfd;
    }
    <div class="color-box box-01">
      <div class="hex-color-code-01">#ffffff</div>
    </div>
    <div class="color-box box-02">
      <div class="hex-color-code-02">#ffffff</div>
    </div>
    <div class="color-box box-03">
      <div class="hex-color-code-03">#ffffff</div>
    </div>
    <button class="change-button">Generate Palette</button>

    【讨论】:

      【解决方案3】:

      hexcode = () => {
              const hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
              let hex = '#';
              for (let i = 0; i < 6; i++) {
                  let index = Math.floor(Math.random() * hexValues.length);
                  hex += hexValues[index];
              }
              return hex;
           }
      console.log(hexcode());

      这个函数会生成一个随机的十六进制。

      let activeHex1 = hexcode();
      

      【讨论】:

        【解决方案4】:

        const hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
        document.querySelector('.change-button').addEventListener("click", () => {
          document.querySelector('.change-button').innerHTML = 'Generate New Palette';
          let activeHex = [];
          for (let i = 0; i < 3; i++) {
            activeHex[i] = '#';
            for (let j = 0; j < 6; j++) {
              activeHex[i] += hexValues[Math.floor(Math.random() * hexValues.length)];
            }
            document.querySelector('.box-' + i).style.backgroundColor = (document.querySelector('.hex-color-code-' + i).innerHTML = activeHex[i]);
          }
        });
        * {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
        }
        
        body {
          height: 100vh;
          width: 100vw;
          font-family: arial, sans-serif;
          font-size: 1rem;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        
        .color-box {
          width: 33.333%;
          height: 100%;
          border: 1px solid black;
          text-transform: uppercase;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #ffffff;
        }
        
        button {
          background: none;
          border: 2px solid #000;
          bottom: 1rem;
          border-radius: 50px;
          padding: 1rem;
          position: fixed;
          font-family: arial, sans-serif;
          font-size: 0.8rem;
          text-transform: uppercase;
          color: #000;
          cursor: pointer;
        }
        
        button:hover {
          background-color: rgba(255, 255, 255, 0.3);
        }
        
        button:active {
          color: #fdfdfd;
          border-color: #fdfdfd;
        }
        <div class="color-box box-0">
          <div class="hex-color-code-0">#ffffff</div>
        </div>
        <div class="color-box box-1">
          <div class="hex-color-code-1">#ffffff</div>
        </div>
        <div class="color-box box-2">
          <div class="hex-color-code-2">#ffffff</div>
        </div>
        <button class="change-button">Generate Palette</button>

        【讨论】:

          【解决方案5】:

          你可以像这样使用一个循环:

            for (let i = 0; i < 6; i++) {
              const indexBox1 = Math.floor(Math.random() * hexValues.length);
              activeHex1 += hexValues[indexBox1];
              
              const indexBox2 = Math.floor(Math.random() * hexValues.length);
              activeHex2 += hexValues[indexBox2];
              
              const indexBox3 = Math.floor(Math.random() * hexValues.length);
              activeHex3 += hexValues[indexBox3];
            }
          

          希望这是你的想象?。

          【讨论】:

            【解决方案6】:

            请在我使用一个循环完成的地方使用以下代码:

               for (let i = 0; i < 6; i++) {
                const indexBox1 = Math.floor(Math.random() * hexValues.length);
                const indexBox2 = Math.floor(Math.random() * hexValues.length);
                const indexBox3 = Math.floor(Math.random() * hexValues.length);
                
                activeHex1 += hexValues[indexBox1];
                activeHex2 += hexValues[indexBox2];
                activeHex3 += hexValues[indexBox3];
              }
            

            这里是 jsfiddle:https://jsfiddle.net/0yhubLn1/

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-11-07
              • 2012-02-19
              • 2013-04-02
              • 2018-04-02
              • 2011-03-09
              • 2016-02-20
              • 2010-12-07
              相关资源
              最近更新 更多