将RGB转换为十六进制问题



根据我尝试创建自己的RGB到HEX COLLOS CONTERTER的stackoverflow主题之一。

我不知道为什么,而是将其转换为双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);
    }
}

i执行准备功能,lol变量是应包含以十六进制格式转换的颜色的变量。

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

说明:

这是因为您将字符串不是将数字传递给supportFunc

prepareAndExecutematch的结果是一系列字符串,因此,当您在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 +

最新更新