현재 색상에 따라 반대 색상을 생성하려면 어떻게 해야 합니까?
저는 현재 색상과 반대되는 색상을 만들려고 합니다.현재 색상이 검은색이면 흰색을 생성해야 합니다.
사실 저는 텍스트를 가지고 있습니다. (이 텍스트의 색은 동적이며, 임의로 색을 만들 수 있습니다.)해당 텍스트는 다음과 같습니다.div
그리고 나는 그 텍스트의 반대 색을 설정해야 합니다.background-color
의div
나는 그 텍스트가 명확하기를 원합니다.div
(색상 원근법).
반대 색상은 Dark / Bright를 의미합니다.
현재 텍스트 색상을 가지고 있으며 이 기능에 전달할 수 있습니다.
var TextColor = #F0F0F0; // for example (it is a bright color)
function create_opp_color(current color) {
// create opposite color according to current color
}
create_opp_color(TextColor); // this should be something like "#202020" (or a dark color)
당신이 만든 아이디어가 있나요?create_opp_color()
기능?
업데이트: GitHub의 프로덕션 준비 코드입니다.
제가 할 수 있는 방법은 다음과 같습니다.
- HEX를 RGB로 변환
- R, G 및 B 성분 반전
- 각 구성 요소를 HEX로 다시 변환합니다.
- 각 구성 요소에 0과 출력을 입력합니다.
function invertColor(hex) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
// invert color components
var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
// pad each with zeros and return
return '#' + padZero(r) + padZero(g) + padZero(b);
}
function padZero(str, len) {
len = len || 2;
var zeros = new Array(len).join('0');
return (zeros + str).slice(-len);
}
출력 예:
고급 버전:
이것은bw
검은색으로 전환할지 흰색으로 전환할지 결정하는 옵션입니다. 따라서 일반적으로 인간의 눈에 더 좋은 대비를 얻을 수 있습니다.
function invertColor(hex, bw) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
var r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16);
if (bw) {
// https://stackoverflow.com/a/3943023/112731
return (r * 0.299 + g * 0.587 + b * 0.114) > 186
? '#000000'
: '#FFFFFF';
}
// invert color components
r = (255 - r).toString(16);
g = (255 - g).toString(16);
b = (255 - b).toString(16);
// pad each with zeros and return
return "#" + padZero(r) + padZero(g) + padZero(b);
}
출력 예:
심플하고 우아합니다.
function invertHex(hex) {
return (Number(`0x1${hex}`) ^ 0xFFFFFF).toString(16).substr(1).toUpperCase()
}
invertHex('00FF00'); // Returns FF00FF
CSS로 이를 달성하는 간단한 방법:
mix-blend-mode: difference;
color:white;
@Onur의 답변 bw 파트의 순수 CSS 구현.
<input type="color" oninput="['--r','--g','--b'].forEach((k,i)=>this.nextElementSibling.style.setProperty(k,parseInt(event.target.value.slice(1+i*2,3+i*2),16)))" />
<div style="--r: 0; --g: 0; --b: 0; --c: calc(-1 * ((var(--r) * 0.299 + var(--g) * 0.587 + var(--b) * 0.114) - 186) * 255)">
<div style="background-color: rgb(var(--r), var(--g), var(--b)); color: rgb(var(--c), var(--c), var(--c))">Test</div>
</div>
CSS는 어때요?filter: invert(1)
텍스트, 이미지 또는 콘텐츠와 호환되는 적절한 교차 호환성을 제공합니다.
흑백 반전 컬러의 경우 필터를 추가하여filter: saturate(0) grayscale(1) brightness(.7) contrast(1000%) invert(1)
다음은 ColorPicker의 예입니다(텍스트 색상 참고).
const colorPicker = document.querySelector("input");
const background = document.querySelector("div");
const invertedText = document.querySelector("b");
colorPicker.oninput = (e) => {
const color = e.target.value;
background.style.background = color;
invertedText.style.color = color;
invertedText.innerText = color;
}
body {
font-family: Arial;
background: #333;
}
div {
position: relative;
display: inline-flex;
justify-content: center;
align-items: center;
min-width: 100px;
padding: .5em 1em;
border: 2px solid #FFF;
border-radius: 15px;
background: #378ad3;
}
b {
/* Inverting the color ᐯᐯᐯᐯᐯᐯᐯᐯᐯᐯᐯᐯ */
filter: saturate(0) grayscale(1) brightness(.7) contrast(1000%) invert(1);
}
input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
<div>
<b>#378ad3</b>
<input type="color" value="#378ad3"/>
</div>
내게 필요한 옵션(AA/AAA)을 주의하십시오.색상 대비 자체는 쓸모가 없습니다.정말 다른 색은 색맹인 사람들에게는 전혀 대비가 될 수 없습니다.IMHO 이러한 색상에 대한 계산은 다음과 같습니다.
(간단하게 사용하려면 "HLS" 사용)
- 색상 180° 회전으로 최대 색상 대비를 얻을 수 있습니다.
- 밝기 차이를 계산합니다.
- (색상 차이 계산...불필요하게, 그것은 최대이거나 거의 )
- 대비 비율 계산.
- 결과 색상이 요구 사항 계산을 준수하는 경우, 그렇지 않은 경우 루프:
- Brightness Difference가 충분하지 않을 경우 계산된 색 광도(L)를 일정량 또는 비율만큼 증가시키거나 감소시킵니다(원래 색 밝기에 따라 위 또는 아래). > 또는 < 중간 값보다 위 또는 아래).
- 요구 사항을 충족하는지, 계산이 종료되는지 확인합니다.
- 광도를 더 이상 증가(또는 감소)시킬 수 있는 경우 요구 사항을 충족할 수 있는 유효한 색상이 없습니다. 검은색과 흰색을 사용하고, 그 중 "가장 좋은 색상"을 선택한 다음(대비비가 더 큰 색상을 선택) 종료하십시오.
당신의 질문에 대한 제가 이해하기로는 반대색이란 역색을 말하는 것입니다.
InvertedColorComponent = 0xFF - ColorComponent
따라서 빨간색(#FF0000)의 경우 R = 0xFF 또는 255G = 0x00 또는 0B = 0x00 또는 0입니다.
반전 색상 빨간색(#00FFFF)은 다음과 같습니다.
R = 0xFF - 0xFF = 0x00 or 255 - 255 = 0
G = 0xFF - 0x00 = 0xFF or 255 - 0 = 255
B = 0xFF - 0x00 = 0xFF or 255 - 0 = 255
다른 예:
검은색(#000000)이 흰색(#FFFF)이 됩니다.
오렌지(#FFA500)가 #005AFF가 됨
이 기능은 16진수 색상을 반전시키는 간단한 기능입니다.
const invertColor = (col) => {
col = col.toLowerCase();
const colors = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
let inverseColor = '#'
col.replace('#','').split('').forEach(i => {
const index = colors.indexOf(i)
inverseColor += colors.reverse()[index]
})
return inverseColor
}
예를 들어 일부 중간 범위 값에서는 배경색을 텍스트 색으로 뒤집는 것만으로는 작동하지 않습니다.0x808080
색 했습니다 - 대신색값바고했습다니려꾸을상다했▁i니습.(v + 0x80) % 0x100
여기에서 데모를 참조하십시오.
미겔-svq의 의견에 동의함 - 각 계산 단계에서 더 자세한 알고리즘을 볼 수 있기를 기대함.
스니펫을 사용하여 HEX 색상을 변환할 수 있습니다.
function invertColor(color) {
return '#' + ("000000" + (0xFFFFFF ^ parseInt(color.substring(1),16)).toString(16)).slice(-6);
}
요소의 색상을 반전하는 기능.각 색상의 밝기를 가져오고 근접한 경우 텍스트 색상을 반전시킵니다.
function adjustColor(element) {
var style = window.getComputedStyle(element);
var background = new Color(style['background-color']);
var text = new Color(style['color']);
if (Math.abs(background.luma - text.luma) < 100) {
element.style.color = text.inverted.toString();
}
}
아래 색상 "클래스".16진수, rgba, rgba(백분율 포함)를 사용할 수 있으며 둘 중 하나로도 출력할 수 있습니다.탐색기에 String.padStart 및 String.starts에 대한 폴리필이 필요합니다.toString() 메서드의 With 및 보간된 문자열은 concat을 대신 사용하여 수정해야 합니다.
const Color = (function () {
function toHex(num, padding) { return num.toString(16).padStart(padding || 2); }
function parsePart(value) {
var perc = value.lastIndexOf('%');
return perc < 0 ? value : value.substr(0, perc);
}
function Color(data) {
if (arguments.length > 1) {
this[0] = arguments[0];
this[1] = arguments[1];
this[2] = arguments[2];
if (arguments.length > 3) { this[3] = arguments[3]; }
} else if (data instanceof Color || Array.isArray(data)) {
this[0] = data[0];
this[1] = data[1];
this[2] = data[2];
this[3] = data[3];
} else if (typeof data === 'string') {
data = data.trim();
if (data[0] === "#") {
switch (data.length) {
case 4:
this[0] = parseInt(data[1], 16); this[0] = (this[0] << 4) | this[0];
this[1] = parseInt(data[2], 16); this[1] = (this[1] << 4) | this[1];
this[2] = parseInt(data[3], 16); this[2] = (this[2] << 4) | this[2];
break;
case 9:
this[3] = parseInt(data.substr(7, 2), 16);
//Fall Through
case 7:
this[0] = parseInt(data.substr(1, 2), 16);
this[1] = parseInt(data.substr(3, 2), 16);
this[2] = parseInt(data.substr(5, 2), 16);
break;
}
} else if (data.startsWith("rgb")) {
var parts = data.substr(data[3] === "a" ? 5 : 4, data.length - (data[3] === "a" ? 6 : 5)).split(',');
this.r = parsePart(parts[0]);
this.g = parsePart(parts[1]);
this.b = parsePart(parts[2]);
if (parts.length > 3) { this.a = parsePart(parts[3]); }
}
}
}
Color.prototype = {
constructor: Color,
0: 255,
1: 255,
2: 255,
3: 255,
get r() { return this[0]; },
set r(value) { this[0] = value == null ? 0 : Math.max(Math.min(parseInt(value), 255), 0); },
get g() { return this[1]; },
set g(value) { this[1] = value == null ? 0 : Math.max(Math.min(parseInt(value), 255), 0); },
get b() { return this[2]; },
set b(value) { this[2] = value == null ? 0 : Math.max(Math.min(parseInt(value), 255), 0); },
get a() { return this[3] / 255; },
set a(value) { this[3] = value == null ? 255 : Math.max(Math.min(value > 1 ? value : parseFloat(value) * 255, 255), 0); },
get luma() { return .299 * this.r + .587 * this.g + .114 * this.b; },
get inverted() { return new Color(255 - this[0], 255 - this[1], 255 - this[2], this[3]); },
toString: function (option) {
if (option === 16) {
return '#' + toHex(this.r) + toHex(this.g) + toHex(this.b) + (this[3] === 255 ? '' : toHex(this[3]));
} else if (option === '%') {
if (this.a !== 1) {
return `rgba(${this.r / 255 * 100}%, ${this.b / 255 * 100}%, ${this.g / 255 * 100}%, ${this.a / 255})`;
} else {
return `rgb(${this.r / 255 * 100}%, ${this.b / 255 * 100}%, ${this.g / 255 * 100})%`;
}
} else {
if (this.a !== 1) {
return `rgba(${this.r}, ${this.b}, ${this.g}, ${this.a})`;
} else {
return `rgb(${this.r}, ${this.b}, ${this.g})`;
}
}
}
};
return Color;
}());
오누르의 답변에 대한 파이썬 대안:
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def invertColor(color, bw=False):
# strip the # from the beginning
color = color.lstrip('#')
# convert the string into hex
color = int(color, 16)
# invert the three bytes
# as good as substracting each of RGB component by 255(FF)
comp_color = 0xFFFFFF ^ color
# convert the color back to hex by prefixing a #
comp_color = "#%06X" % comp_color
rgb_color = hex_to_rgb(comp_color)
if (bw):
# http://stackoverflow.com/a/3943023/112731
bw_value = rgb_color[0]*0.299 + rgb_color[0]*0.587 + rgb_color[0]*0.114
if (bw_value>186):
comp_color = "#FFFFFF"
else:
comp_color = "#000000"
# return the result
return comp_color
color = "#fffff1"
print invertColor(color, bw=True)
Typescript 애호가를 위해 사용되는 내용:
invertHex(hex: string) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
if (hex.length != 6) {
console.warn('Hex color must be six hex numbers in length.');
return '#' + hex;
}
hex = hex.toUpperCase();
const splitNum = hex.split('');
let resultNum = '';
const simpleNum = 'FEDCBA9876'.split('');
const complexNum = {
A: '5', B: '4', C: '3', D: '2', E: '1', F: '0'
};
for (let i = 0; i < 6; i++) {
if (!isNaN(Number(splitNum[i]))) {
resultNum += simpleNum[splitNum[i]];
} else if (complexNum[splitNum[i]]) {
resultNum += complexNum[splitNum[i]];
} else {
console.warn('Hex colors must only include hex numbers 0-9, and A-F');
return '#' + hex;
}
}
return '#' + resultNum;
}
function getContrastColor(color) {
var hex = color.replace(/#/, '');
var red = parseInt(hex.substr(0, 2), 16);
var green = parseInt(hex.substr(2, 2), 16);
var blue = parseInt(hex.substr(4, 2), 16);
var luminance = (0.2126 red + 0.7152 green + 0.0722 * blue) / 255;
return luminance > 0.5 ? '#000000' : '#ffffff';
}
var contrastColor = getContrastColor("#FFFFFF");
console.log(contrastColor);
언급URL : https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color
'programing' 카테고리의 다른 글
dict to txt 파일을 쓰고 다시 읽는 중? (0) | 2023.08.17 |
---|---|
스위프트의 if Let은 어떻게 평가됩니까? (0) | 2023.08.17 |
사용자가 Android 활동을 종료할지 확인하는 대화 상자를 표시하는 방법은 무엇입니까? (0) | 2023.08.17 |
jQueryUniform 라이브러리를 사용하여 확인란을 선택 취소하는 방법 (0) | 2023.08.17 |
dataType jsonp와 JSON의 차이 (0) | 2023.08.17 |