如何在给定计数器的情况下以“彩虹顺序”生成一系列十六进制代码?

时间:2019-01-18 04:54:30

标签: javascript css colors hex background-color

编辑:我在这里仍然想出一些代码(现在是255个对象):

for (let i = 1; i <= 255; i++) {
  let arg = document.createElement("div");
  let red = 0;
  let green = 0;
  let blue = 0;
  if (color == 0) {
    red = 255;
    green = num * 3;
  } else if (color == 1) {
    red = 255 - num*3;
    green = 255;
    blue = num * 3;
  } else if (color == 2) {
    red = num * 3;
    green = 255-num*3;
    blue = 255; 
  }
  arg.style.backgroundColor = "#" + htd(red) + htd(green) + htd(blue);
  document.querySelector("body").appendChild(arg);
  if (num == 85) {
    num = 1;
    color++;
  } else {
    num++;
  }
}

老问题

我正在使用for循环在JS中生成许多HTML对象。我希望这些对象逐渐从红色变为紫色(彩虹顺序)。我将如何从#FF0000#008080再回到#FF0000

到目前为止,这是我的代码(效果不佳):

for (let i = 1; i < 255; i++) {
   let arg = document.createElement("div");
   let num = i;
   if (num > 255) {
      num = 255;
   }
   let red = 255;
   let blue = 0;
   if (num < 128) {
     let green = 0;
     arg.style.backgroundColor = "#" + htd(red - i) + htd(green + i * 2) + htd(blue + i);
   } else {
     let green = 256;
     arg.style.backgroundColor = "#" + htd(red - i * 2) + htd(green - i * 2) + htd(blue + i);
   }
   document.querySelector("body").appendChild(arg);
}

function htd(num) {
   let hexString = num.toString(16);
   if (hexString.length % 2) {
      hexString = '0' + hexString;
   }
   return hexString;
}

如果您想了解为什么我需要这样做,请转到https://codepen.io/navinate/pen/dwExxm

谢谢!

1 个答案:

答案 0 :(得分:0)

我想你想要的是

  1. 色调值的梯度
  2. 从HSL(色相,饱和度,亮度)到RGB的转换
  3. RGB至#hex表示法,您已经介绍过

色调的梯度是一个简单的线性插值问题:

const length = 100;
const hueGradient = Array.from({length}, (v, k) => k/(length-1));

this question的答案中可以找到从HSL到RGB的示例转换。使用它:

const saturation = 1.0;
const lightness = 0.5;
const rgbValues = hueGradient.map(hue => hslToRgb(hue, saturation, lightness));

结果是一个[R, G, B]数组,您可以将其表示为#rgb个值:

const htmlRgbValues = rgbValues.map(([r,g,b]) => `#${htd(r)}${htd(g)}${htd(b)}`);

很有可能您不想使用查找表,而是想即时进行插值,只需使用

const htmlRgbValue = hslToRgb(x / x_max, saturation, lightness);