2017-09-16 46 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 +