Skip to content

Commit

Permalink
even better coloring
Browse files Browse the repository at this point in the history
  • Loading branch information
ThinLiquid committed May 15, 2024
1 parent 216b5c5 commit 0c375f4
Showing 1 changed file with 14 additions and 28 deletions.
42 changes: 14 additions & 28 deletions src/color.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const threshold = 0.9
const threshold = 0.75

class Color {
/**
Expand Down Expand Up @@ -77,42 +77,28 @@ class Color {
* @returns The adjusted color
*/
adjustContrastColor (color: string): string | null {
// Parse the color
let r
let g
let b

// Check if the color is in hex or rgb format
if (color.startsWith('#')) {
color = color.substring(1)
r = parseInt(color.substr(0, 2), 16)
g = parseInt(color.substr(2, 2), 16)
b = parseInt(color.substr(4, 2), 16)
} else if (color.startsWith('rgb(') && color.endsWith(')')) {
const rgb = color.substring(4, color.length - 1).split(',')
r = parseInt(rgb[0])
g = parseInt(rgb[1])
b = parseInt(rgb[2])
r = parseInt(color.slice(1, 3), 16)
g = parseInt(color.slice(3, 5), 16)
b = parseInt(color.slice(5, 7), 16)
} else {
return null
}

// Calculate the luminance of the color and adjust the color
if ((0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > threshold) {
r = Math.max(0, r - 100)
g = Math.max(0, g - 100)
b = Math.max(0, b - 100)
} else {
r = Math.min(255, r + 100)
g = Math.min(255, g + 100)
b = Math.min(255, b + 100)
}
// Calculate the perceived luminance
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255

// Adjust the color based on the luminance
const adjustment = luminance < threshold ? 10 : -10
r = Math.max(0, Math.min(255, r + adjustment))
g = Math.max(0, Math.min(255, g + adjustment))
b = Math.max(0, Math.min(255, b + adjustment))

// Return the adjusted color
return color.startsWith('#')
? `#${((1 << 24) + (r << 16) + (g << 8) + b)
.toString(16)
.slice(1)}`
: `rgb(${r},${g},${b})`
return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
}
}

Expand Down

0 comments on commit 0c375f4

Please sign in to comment.