U
U
Uncle_Bens2019-01-30 20:14:46
JavaScript
Uncle_Bens, 2019-01-30 20:14:46

How to decrease value like #cef1ff?

There is an array of values, values ​​of the form #000000.
Each value needs to be changed on the fly to a constant, for example #110011.
You need to get a variable that will be equal to the difference from the array and the constant.
The whole plug is in the arithmetic itself, such as subtracting #110011 from the finished #cef1ff to get #bdf1ee?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Soslan Khloev, 2019-01-30
@Uncle_Bens

We cut off the lattice, translate the result from hex into an integer, subtract, translate the result into hex, insert # in front

let result = parseInt('#cef1ff'.substr(1), 16) - parseInt('#110011'.substr(1), 16);
console.log('#' + result.toString(16).padStart(6, '0'));

I
Interface, 2019-01-30
@Interface

As a solution with bit overflow and 3-character color handling

function hexToTriple(hex) {
    hex = hex.slice(1);
    if (hex.length === 3) {
        return hex.split('').map(byte => parseInt(byte.repeat(2), 16));
    } else if (hex.length === 6) {
        return hex.match(/.{2}/g).map(byte => parseInt(byte, 16));
    } else {
        throw new Error(`invalid color ${hex}`);
    }
}

function tripleToHex(triple) {
    return '#' + triple.map(byte => byte.toString(16).padStart(2, '0')).join('');
}

function hexColorSubtract(hexAColor, hexBColor) {
    const [tripleA, tripleB] = [hexAColor, hexBColor].map(hexToTriple);
    const resultTriple = tripleA.map((byte, index) => {
        return Math.max(byte - tripleB[index], 0);
    });
    return tripleToHex(resultTriple);
}

// использование:

hexColorSubtract("#cef", "#110011"); // #bbeeee

S
Sergey Sokolov, 2019-01-30
@sergiks

function hexColorSubtract(ca, cb) {
    const a = parseInt(ca.substring(1), 16);
    const b = parseInt(cb.substring(1), 16);
    return '#' + ('000000' + Math.max(0, a-b).toString(16)).slice(-6).toUpperCase();
  }
  
  hexColorSubtract("#cef1ff", "#110011"); // #BDF1EE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question