根据 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);
}
}
我执行 prepare 函数,lol
变量应该包含十六进制格式的转换颜色。
我的代码有什么问题,为什么它不起作用?
最佳答案
解释:
这是因为您将字符串而不是数字传递给 supportFunc
。
prepareAndExecute
中的match
的结果是一个字符串数组,因此当您在supportFunc
中调用toString
时,您正在调用 String.prototype.toString
(不是 Number.prototype.toString
),它按原样返回字符串。
解决方案:
在 supportFunc
中,在使用 toString
之前将 number
转换为数字:
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 +
关于javascript - 将 RGB 转换为 HEX 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255635/