2017-09-16 52 views
3

我试图创建自己的RGB到HEX颜色转换器。根据StackOverflow主题之一将RGB转换为HEX问题

我不知道为什么,而是将其转换为双RGB数字。

所以当输入是rgb(0, 128, 192)它控制台出#00128192

我的代码是:

fromRGB: { 
    toHEX: { 
     supportFunc: function(number) { 
      var hex = number.toString(16); 
      return hex.length == 1 ? '0' + hex : hex; 
     }, 
     convert: function(r, g, b) { 
      var lol = '#' + this.supportFunc(r) + this.supportFunc(g) + this.supportFunc(b); 
      console.log(lol); 
     } 
    }, 
    prepareAndExecute: function(color_field) { 
     // preparing 
     var numbers = color_field.match(/\d+/g); 
     if(numbers.length == 3) { 
      this.toHEX.convert(numbers[0], numbers[1], numbers[2]); 
     } else { 
      alert('wrong RGB number format'); 
     } 


     //this.toHSL(preparedValue); 
    } 
} 

我执行准备功能,lol变量是应包含在十六进制格式转换的色彩的一个。

我的代码有什么问题,为什么它不起作用?

+1

'.match( )'返回一个**字符串**数组,而不是数字。 – Pointy

+0

可能重复[RGB到十六进制和十六进制到RGB](https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb) –

+0

@KenWhite我认为OP已经使用该重复链接上面提出他的代码。但是他遇到了一个问题(字符串为数字),与如何获取值无关。因此将其标记为与该链接重复是错误的。 –

回答

1

说明:

这是因为你传递字符串而不是数字来supportFunc

prepareAndExecutematch的结果是一个字符串数组,从而当调用在supportFunctoString,您呼叫String.prototype.toString(未Number.prototype.toString),其返回的字符串为是。

解决方案:

supportFunc,转换number到多个使用toString之前:

var hex = Number(number).toString(16);      // using Number to convert a string to a number (you can use parseInt or unary + if you like) 

或他们将它们传递给convert之前转换:

this.toHEX.convert(+numbers[0], +numbers[1], +numbers[2]); // using unary +