Javascript - Converting colors (numbers -> strings) vice versa

后端 未结 1 559
终归单人心
终归单人心 2021-01-13 00:23
utils.parseColor = function (color, toNumber) {
  if (toNumber === true) {
    if (typeof color === \'number\') {
      return (color | 0); //chop off decimal
    }
         


        
相关标签:
1条回答
  • 2021-01-13 01:08

    | in JavaScript is bitwise OR. In this case, all it does is force the number to be an integer.

    Bitwise OR takes two numbers and compares all their bits. If either bit is a 1, the result has a 1 there. So, given the two binary numbers 1100 and 1010 you would get the following:

    1100
    1010
    ----
    1110
    

    As you can see, the result has a 1 in every column that has a 1. So | 0 does not change the value of the number.

    However, because it works with the binary representation of integers, JavaScript changes the number to an integer before applying it. This means that 2.3 | 0 is 2 in JavaScript.

    You have to make sure the number is padded properly because the color format expects six digits. That is, #00F000 is valid where #F000 is not.

    The way it works is simple. Lets say you pass in 34 as your color number. 0x22 is "22" as a string in base 16. (The call to toString(n) on a number returns the representation of the number in base n.) This is not a valid color because colors need six digits after the # (in CSS you can also have three, but that's not important). So what they do is first add five 0s as a string. This means "22" becomes "0000022". Finally, the take the last six characters from this: 000022. (Calling substr with a negative index counts from the end of the string.) This gives them a valid color.

    So, putting it all together, the line

    color = '#' + ('00000' + (color | 0).toString(16)).substr(-6); 
    

    takes the number you passed in, turns it into an integer with (color | 0), turns it into a hexadecimal string with .toString(16), pads it with a bunch of zeroes, takes the last six characters from the padded string and prepends a # to it.

    This is actually a fairly clever and elegant way to write this function.

    0 讨论(0)
提交回复
热议问题