Convert rgb strings to hex in Javascript

前端 未结 8 1150
借酒劲吻你
借酒劲吻你 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 01:51

    This is what I did.

    String.prototype.toRGB = function() {
    
      var rgb = this.split( ',' ) ;
      this.r=parseInt( rgb[0].substring(4) ) ; // skip rgb(
      this.g=parseInt( rgb[1] ) ; // this is just g
      this.b=parseInt( rgb[2] ) ; // parseInt scraps trailing )
    
    }
    

    After you run 'rgb(125,181,215)'.toRGB(), you will get .r, .g and .b properties defined (with correct integer values) in the same string object returned.

    To get the hex value, simply use yourNumber.toString(16);

提交回复
热议问题