简体   繁体   中英

Javascript. Find the Inverse of a Hex code

I was just working with HTML hex color codes and wondered if there is any easy way to calculate the inverse of any color code using plan javascript.

const hex = "#xxxxxx";
const inverseHex = "#yyyyyy";

const add = hex + inverseHex; // #000000

My 50 cents:

 const inv = (hex) => '#' + hex.match(/[a-f0-9]{2}/ig).map(e => (255 - parseInt(e, 16) | 0).toString(16).replace(/^([a-f0-9])$/, '0$1')).join('') const invert = () => document.querySelectorAll('circle') .forEach(c => (hex = c.getAttribute('fill')) && c.setAttribute('fill', inv(hex)) ) console.log('#000000', inv('#000000')) console.log('#ffffff', inv('#ffffff')) console.log('#ff6600', inv('#ff6600')) console.log('#fe4289', inv('#fe4289')) 
 body { background: grey } svg { width: 45px; height: 45px; display: inline-block; margin: 10px } 
 <svg><circle cx="20" cy="20" r="20" fill="#000000"/></svg> <svg><circle cx="20" cy="20" r="20" fill="#ffffff"/></svg> <svg><circle cx="20" cy="20" r="20" fill="#ff6600"/></svg> <svg><circle cx="20" cy="20" r="20" fill="#fe4289"/></svg> <p><button onclick="invert()">Invert!</button></p> 

 function inverse(figure) { // inverse a RGB color return ((figure & 0x000000) | (~figure & 0xFFFFFF)) } var a = document.querySelector('#a') var b = document.querySelector('#b') var color = "#FF00FF" var inversedColor = "#" + inverse(parseInt(color.substr(1), 16)) .toString(16) .padStart(6, "0") .toUpperCase(); a.style.background = color; b.style.background = inversedColor; console.log(color, inversedColor); 
 <button id=a>Button A</button> <button id=b>Button B</button> 

credits for the inverse function : https://stackoverflow.com/a/44387888/750852

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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