Skip to content

Instantly share code, notes, and snippets.

@typeofweb
Created July 28, 2021 13:47
Show Gist options
  • Save typeofweb/da7720fc245fa2f412aeb7b08c808a37 to your computer and use it in GitHub Desktop.
Save typeofweb/da7720fc245fa2f412aeb7b08c808a37 to your computer and use it in GitHub Desktop.
function getHexValue(intInput: number) {
return intInput.toString(16).padStart(2, "0");
}
function getTintValue(tint: number, bgTint: number, alpha: number) {
return Math.min(Math.floor((1 - alpha) * bgTint + alpha * tint), 255);
}
class Color {
constructor(
public red: number, // 0-255
public green: number, // 0-255
public blue: number, // 0-255
public alpha: number = 1 // 0-1
) {}
static fromRgba(rgba: string) {
const [r, g, b, a] = rgba.replace(/[^\d\.,]/g, "").split(",");
return new Color(
parseInt(r, 10),
parseInt(g, 10),
parseInt(b, 10),
parseFloat(a)
);
}
static fromHex(hex: string) {
const [r, g, b] = hex
.replace(/[^\da-z]/g, "")
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
return new Color(r, g, b);
}
equals(other: Color) {
return (
this.red === other.red &&
this.green === other.green &&
this.blue === other.blue &&
this.alpha === other.alpha
);
}
compare(other: Color) {
return Math.sqrt(
Math.pow(this.red - other.red, 2) +
Math.pow(this.green - other.green, 2) +
Math.pow(this.blue - other.blue, 2)
);
}
toHex() {
return (
"#" +
getHexValue(this.red) +
getHexValue(this.green) +
getHexValue(this.blue)
);
}
}
function performcalculation(rgbaColor: Color, backgroundColor: Color) {
const result = new Color(
getTintValue(rgbaColor.red, backgroundColor.red, rgbaColor.alpha),
getTintValue(rgbaColor.green, backgroundColor.green, rgbaColor.alpha),
getTintValue(rgbaColor.blue, backgroundColor.blue, rgbaColor.alpha)
);
return result;
}
function findBeMatchFor(backgroundColor: Color, expected: Color) {
const results: { result: Color; rgbaColor: Color }[] = [];
for (let a = 0; a <= 1; a += 0.001) {
const rgbaColor = Color.fromRgba(`rgba(0,0,0,${a})`);
const result = performcalculation(rgbaColor, backgroundColor);
results.push({ result, rgbaColor });
}
const finalResult = results.reduce(
(acc, r) => {
const c = r.result.compare(expected);
if (c < acc.comparison) {
return { result: r, comparison: c };
}
return acc;
},
{
result: null as { result: Color; rgbaColor: Color } | null,
comparison: Infinity,
}
);
return finalResult;
}
{
const backgroundColor = Color.fromHex("#73b588");
const expected = Color.fromHex("#375841");
console.log(findBeMatchFor(backgroundColor, expected).result.rgbaColor);
}
{
const backgroundColor = Color.fromHex("#301cd2");
const expected = Color.fromHex("#342a84");
console.log(findBeMatchFor(backgroundColor, expected).result.rgbaColor);
}
{
const backgroundColor = Color.fromHex("#cf3c96");
const expected = Color.fromHex("#7d3261");
console.log(findBeMatchFor(backgroundColor, expected).result.rgbaColor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment