【问题标题】:Javascript. Find the Inverse of a Hex codeJavascript。求十六进制码的倒数
【发布时间】:2019-01-05 04:15:08
【问题描述】:

我刚刚使用 HTML 十六进制颜色代码,想知道是否有任何简单的方法可以使用计划 javascript 计算任何颜色代码的倒数。

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

const add = hex + inverseHex; // #000000

【问题讨论】:

标签: javascript html hex inverse


【解决方案1】:

我的 50 美分:

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>

【讨论】:

    【解决方案2】:

    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>

    反函数的功劳:https://stackoverflow.com/a/44387888/750852

    【讨论】:

    • 似乎function inverse (figure) {return 0xFFFFFF - figure} 会更容易一些。不是一样的吗?
    • 使用 (0x00FFFFFF - (rgba | 0xFF000000)) | (RGB & 0xFF000000);如果你不想让不透明的白色变成透明的黑色。
    • 关于figure &amp; 0x000000 (anything &amp; 0) === 0
    猜你喜欢
    • 2023-01-29
    • 1970-01-01
    • 2020-06-15
    • 2016-01-05
    • 1970-01-01
    • 2013-06-10
    • 2017-05-29
    • 2014-11-03
    • 2016-04-17
    相关资源
    最近更新 更多