class ColorManipulator {
private baseColor: string
private targetColor: string
constructor(baseColor: string, targetColor: string) {
this.baseColor = baseColor
this.targetColor = targetColor
}
private hexToRgb(hex: string) {
const bigint = parseInt(hex.slice(1), 16)
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255,
}
}
public calculateOpacity() {
const target = this.hexToRgb(this.targetColor)
const baseRG = this.hexToRgb(this.baseColor)
const opacities = [
(target.r - baseRG.r) / (255 - baseRG.r),
(target.g - baseRG.g) / (255 - baseRG.g),
(target.b - baseRG.b) / (255 - baseRG.b),
]
const averageOpacity =
opacities.reduce((sum, value) => sum + value, 0) / opacities.length
return averageOpacity
}
public getCssRGBA() {
const opacity = this.calculateOpacity()
return `rgba(0, 0, 0, ${opacity.toFixed(2)})`
}
}
const manipulator = new ColorManipulator('#000000', '#D1D7DE')
const opacity = manipulator.calculateOpacity()
const cssRGBA = manipulator.getCssRGBA()