주어진 색상의 상보적인 색상을 결정하는 방법
목표는 주어진 색상과 반대되는 색상을 생성하는 것입니다. 예를 들어, 현재 색상이 검은 색이면 반대는 흰색이어야합니다. 이 작업은 명확한 가시성을 보장하기 위해 역동적 인 색상의 텍스트에 대한 대조적 인 배경색을 설정할 때 중요합니다.
이를 달성하기 위해 다음과 같은 접근 방식을 사용합니다. 상보적인 값을 얻기 위해 색상.
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 component with leading 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); }
예제 출력 :
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) { // Formula to determine if the color is closer to black or white. 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 component with leading zeros and return. return '#' padZero(r) padZero(g) padZero(b); }
예제 출력 :
[] (https://stackshare.io/resources/color-contrast-checker)
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3