Skip to content

Instantly share code, notes, and snippets.

@suhodolskiy
Last active March 30, 2024 03:41
Show Gist options
  • Save suhodolskiy/d14b74e183607bbb34eae3313bce7c80 to your computer and use it in GitHub Desktop.
Save suhodolskiy/d14b74e183607bbb34eae3313bce7c80 to your computer and use it in GitHub Desktop.
Contrasting color [Colord]
import { Plugin } from 'colord'
declare module 'colord/colord' {
interface Colord {
contrasting(): Colord
}
}
const plugin: Plugin = (ColordClass) => {
ColordClass.prototype.contrasting = function () {
const isLight = this.isLight()
let color = this
while(color.contrast(this) < 4.5) color = isLight ? color.darken(0.4) : color.lighten(0.4)
return color
}
}
export default plugin
import { Colord, colord, extend } from 'colord'
import a11yPlugin from 'colord/plugins/a11y'
import contrastingPlugin from './contrasting'
extend([a11yPlugin, contrastingPlugin])
colord('#ebfde8').contrasting().toHex()
@artalar
Copy link

artalar commented Feb 22, 2022

while(color.contrast(this) < 4.5) color = isLight ? color.darken(0.4) : color.lighten(0.4)

@suhodolskiy
Copy link
Author

@artalar Thanks. I have updated

@jd-solanki
Copy link

Infinite loop when passing red color 🤔

@nelson6e65
Copy link

My page got broken using this plugin. Maybe it needs a way to break the infinite loop? 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment