Change text color based on brightness of the covered background area?

前端 未结 8 1600
悲哀的现实
悲哀的现实 2020-11-27 09:53

I\'ve thought about the following for a while already, so now I want to know your opinions, possible solutions, and so on.

I am looking for a plugin or technique tha

8条回答
  •  一向
    一向 (楼主)
    2020-11-27 09:58

    If you are using ES6, convert hex to RGB then can use this:

    const hexToRgb = hex => {
        // turn hex val to RGB
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
        return result
            ? {
                  r: parseInt(result[1], 16),
                  g: parseInt(result[2], 16),
                  b: parseInt(result[3], 16)
              }
            : null
    }
    
    // calc to work out if it will match on black or white better
    const setContrast = rgb =>
        (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000 > 125 ? 'black' : 'white'
    
    const getCorrectColor = setContrast(hexToRgb(#ffffff))
    

提交回复
热议问题