简体   繁体   English

将RGB转换为HEX问题

[英]converting RGB to HEX issue

according to one of StackOverflow topics I tried to create own RGB to HEX colors converter. 根据StackOverflow主题之一,我尝试创建自己的RGB到HEX颜色转换器。

I don't know why but instead converting it double RGB numbers. 我不知道为什么,而是转换它双RGB数字。

So when input is rgb(0, 128, 192) it console out #00128192 . 所以当输入是rgb(0, 128, 192) #00128192 rgb(0, 128, 192)它会调出#00128192

My code is: 我的代码是:

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 execute prepare function, lol variable is the one that should contains converted color in HEX format. 我执行prepare函数, lol变量是应该包含HEX格式的转换颜色的变量。

What is wrong with my code, why it doesn't work? 我的代码有什么问题,为什么它不起作用?

Explanation: 说明:

It's because you're passing strings not numbers to supportFunc . 这是因为你将字符串而不是数字传递给supportFunc

The result of match in prepareAndExecute is an array of strings, thus when you call toString in supportFunc , you are calling String.prototype.toString (not Number.prototype.toString ) which return the string as is. prepareAndExecutematch的结果是一个字符串数组,因此当您在supportFunc调用toString时,您正在调用String.prototype.toString (而不是Number.prototype.toString ),它返回字符串。

Solution: 解:

In supportFunc , convert number to a number before using 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)

or convert them before passing them to convert : 或者将它们传递到之前将它们转换convert

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM