编辑:我有点想通了 这里的代码仍然有一些问题(现在必须是 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
谢谢!
我认为你想要的是
- 色调值的渐变
- 从 HSL(色调、饱和度、亮度)到 RGB 的转换
- RGB 到 #hex 表示法,您已经介绍了
色调梯度是一个简单的线性插值问题:
const length = 100;
const hueGradient = Array.from({length}, (v, k) => k/(length-1));
从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);