JavaScript implements hexadecimal color difference function, hexadecimal color subtraction, replace, parseInt, max, toString, slice

Table of contents


the code

/**
 * 将十六进制颜色转换为RGB格式
 * @param {string} hex 十六进制颜色值
 * @return {string} {r, g, b} 返回最终的rgb值
 */
function hexToRgb(hex) {
    
    
    // 去掉可能的#字符
    hex = hex.replace(/^#/, '');

    // 如果是缩写形式的颜色值(如 #FFF),则将其扩展为完整形式
    if (hex.length === 3) hex = hex.replace(/(.)/g, '$1$1');

    // 解析RGB值
    let bigint = parseInt(hex, 16),
        r = (bigint >> 16) & 255,
        g = (bigint >> 8) & 255,
        b = bigint & 255;

    return {
    
     r, g, b };
}

/**
 * 两种颜色相减后的值
 * @param {string} color1 颜色1(主颜色,一般是大值)
 * @param {string} color2 颜色2
 * @return {object} { hexadecimal, rgb } 返回十六进制和rgb值
 */
function subtractColors(color1, color2) {
    
    
    let rgb1 = hexToRgb(color1),
        rgb2 = hexToRgb(color2),
        r = rgb1.r - rgb2.r,
        g = rgb1.g - rgb2.g,
        b = rgb1.b - rgb2.b,
        reslut = (val) => Math.max(0, val);

    // 将RGB结果转换为十六进制格式
    return {
    
    
        hexadecimal: `#${
      
      (1 << 24 | reslut(r) << 16 | reslut(g) << 8 | reslut(b)).toString(16).slice(1)}`,
        rgb: `${
      
      r}, ${
      
      g}, ${
      
      b}`
    };
}

console.log(subtractColors('ffffff', 'ff0000'));
// {hexadecimal: '#00ffff', rgb: '0, 255, 255'}

replace

w3school

replacemethod searches a string for a value or a regular expression.
replacemethod returns a new string with the value replaced.
replacemethod does not change the original string.
If you replace a value, only the first instance will be replaced. To replace all instances, use ga regular expression with modifier sets.


MDN

replaceThe method returns a new string with replacementsome or all patternmatches of the pattern ( ) replaced by the replacement value ( ). The pattern can be a string or a regular expression, and the replacement value can be a string or a callback function to be called for each match. If patterna string, only the first occurrence is replaced.


parseInt

MDN

parseInt(string, radix)Parses a string and returns a decimal integer in the specified radix, radixwhich is 2-36an integer between, representing the radix of the string being parsed.
string
The value to be parsed. If the argument is not a string, it is converted to a string (using the ToString abstract operation). Whitespace at the beginning of the string will be ignored.
radixOptional Integer
from 2to 36, representing the base of the base. For example, specifying 16that the parsed value is a hexadecimal number. Will return if outside of this range NaN. If specified 0or not specified, the radix will be inferred from the value of the string. =The extrapolated result will not always be the default 10! The description at the end of the article explains radixthe specific behavior of the function when the parameter is not passed.

w3school

parseInt()The function parses the string and returns an integer.
radixThe parameter is used to specify which number system to use, e.g. radix is 16​​(hexadecimal) to indicate that the numbers in the string should be parsed from hexadecimal to decimal.
If radixthe argument is omitted, JavaScriptthe following is assumed:
if the string begins "0x"with , the radix is 16​​(hexadecimal)
If the string "0"starts with , the radix is 8​​(octal). This attribute is deprecated.
If the string starts with any other value, the base is 10(decimal)
Only returns the first number in the string!
Leading and trailing spaces are allowed.
parseInt()Returns if the first character cannot be converted to a number NaN.
== Older browsers will result parseInt("010")in , because 8older versions use an octal radix as the default when the string starts with . From start, the default is base-decimal .ECMAScriptECMAScript5"0"8ECMAScript510


max

MDN

Math.max()The function returns the largest number taken as an input parameter, or -Infinity if there is no parameter .


W3school

max()method returns the number with the highest value.
Tip: The min() method returns the number with the smallest value.


w3school

toString()method returns the object as a string. Return
if the method cannot return a string . Always return the object constructor. method does not change the original object.toString()"[object Object]"
Object.toString()
toString()
Every JavaScriptobject has toString()methods. methods are used internally
when an object needs to be displayed as text (as in HTML) or when an object needs to be used as a string . Normally, you wouldn't use it in your own code.JavaScripttoString()


MDN

toString()method returns a string representing the object. This method is intended to override (customize) the logic of type conversions for derived class objects .


slice

w3school

sliceThe method returns the selected elements in the array with a new array object.
slicemethod selects startelements starting at and ending at, but not including, the given endargument.
slicemethod does not alter the original array.


MDN

sliceThe method returns a new array object, which is a shallow copy of the original array determined by and, inclusive start, excluding , where and represent the index of the array element. The original array will not be changed.endstartendstart end

Guess you like

Origin blog.csdn.net/weixin_51157081/article/details/132639364