如何从一个单一的颜色代码中获得5种颜色的百分比组合



我有一个类似#8B8989的颜色代码

我还有5种不同的颜色代码像

***红色***黄色***蓝色***白色***黑色

现在我必须混合这个颜色代码来生成我的目标颜色代码。

到目前为止我已经尝试了什么---

到目前为止,我试图添加那些颜色十六进制代码,并试图实现我的目标颜色,但到目前为止还没有达到我所期望的

function docalc(colorCode) {
let redCount = 0,
yellowCount = 0;
let oldColor = document.getElementById("output_color_code").value;
if (oldColor != "") {
c = (parseInt(oldColor, 16) + parseInt(colorCode, 16)).toString(16);
console.log(c);
} else {
c = colorCode;
}
document.getElementById("output_color_code").value = c;
document.getElementById("output").style.backgroundColor = c;
let givenColor = document.getElementById("given_color").value;
document.getElementById("given_output").style.backgroundColor = givenColor;
}

我想实现的是在https://trycolors.com/game中实现的,但我没有找到这个的算法

您是否考虑过对十六进制代码的组件进行加权平均?也就是说,如果添加了3种颜色A和2种颜色B,则可以使用十六进制代码#RRGGBB将每种颜色分解为其红色、绿色和蓝色分量。

然后,您的新颜色的红色成分将为(3*Red Component of A + 2*Red Component of B) / (3+2),绿色成分为(3*Green Component of A + 2*Green Component of B) / (3+2),而(3*Blue Component of A + 2*Blue Component of B) / (3+2)

请记住,6位六进制颜色代码的每个分量的最大值为0xFF(十进制255(,因此总和最终只会导致白色(#FFFFFF(。此外,如果您不分离组件,那么当一个组件溢出到另一个组件时,您将看到一些奇怪的颜色行为。

您可以使用以下代码作为指南:

// keep track of how many times colors have already been added in some variable addCounter.  It probably shouldn't be global, but you'll need a way to keep track of this across many function calls.
var addCounter = 0;
function addColor(colorCode) {
let oldColor = document.getElementById("output_color_code").value;
if (oldColor != "") {
// assuming oldColor and newColor do not contain leading '#'
let oldRed = parseInt(oldColor.slice(0,2),16);
let oldGreen = parseInt(oldColor.slice(2,4),16);
let oldBlue = parseInt(oldColor.slice(4,6),16);
let newRed = parseInt(newColor.slice(0,2),16);
let newGreen = parseInt(newColor.slice(2,4),16);
let newBlue = parseInt(newColor.slice(4,6),16);
let avgRed = oldRed * addCounter + newRed;
let avgGreen = oldGreen * addCounter + newGreen;
let avgBlue = oldBlue * addCounter + newBlue;
let c = avgRed.toString(16) + avgGreen.toString(16) + avgBlue.toString(16);
console.log(c);
} else {
c = colorCode;
}

addCounter++;
document.getElementById("output_color_code").value = c;
document.getElementById("output").style.backgroundColor = "#"+c;
let givenColor = document.getElementById("given_color").value;
document.getElementById("given_output").style.backgroundColor =  "#"+c;
}

最新更新