Convert rgb strings to hex in Javascript

前端 未结 8 1161
借酒劲吻你
借酒劲吻你 2021-02-07 01:21

I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always i

8条回答
  •  爱一瞬间的悲伤
    2021-02-07 02:13

    rgb2Hex = s => s.match(/[0-9]+/g).reduce((a, b) => a+(b|256).toString(16).slice(1), '0x')
    
    console.log(rgb2Hex('rgb(10, 11, 12)'), rgb2Hex('rgb(255, 256, 257)'))


    Not recommended for unreliable user input, but the string can also be evaluated as a function:

    rgb = (r, g, b) => '0x' + (1<<24|r<<16|g<<8|b).toString(16).slice(1)
    
    console.log(eval('rgb(10, 11, 12)'), eval('rgb(255)'))

提交回复
热议问题