RGB to hex and hex to RGB

前端 未结 30 3262
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  温柔的废话
    2020-11-21 07:02

    i needed a function that accepts invalid values too like

    rgb(-255, 255, 255) rgb(510, 255, 255)

    this is a spin off of @cwolves answer

    function rgb(r, g, b) {
      this.c = this.c || function (n) {
        return Math.max(Math.min(n, 255), 0)
      };
    
      return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
    }
    

提交回复
热议问题