|
| 1 | +import React, { useState } from "react"; |
| 2 | +import ReactDOM from "react-dom"; |
| 3 | + |
| 4 | +function ContrastChecker() { |
| 5 | + const [foreground, setForeground] = useState("#000000"); |
| 6 | + const [background, setBackground] = useState("#ffffff"); |
| 7 | + |
| 8 | + const checkContrast = () => { |
| 9 | + const contrastRatio = getContrastRatio(foreground, background); |
| 10 | + return contrastRatio >= 4.5 ? "pass" : "fail"; |
| 11 | + }; |
| 12 | + |
| 13 | + const handleForegroundChange = (event) => { |
| 14 | + setForeground(event.target.value); |
| 15 | + }; |
| 16 | + |
| 17 | + const handleBackgroundChange = (event) => { |
| 18 | + setBackground(event.target.value); |
| 19 | + }; |
| 20 | + |
| 21 | + return ( |
| 22 | + <div id="app"> |
| 23 | + <h1>Contrast Checker</h1> |
| 24 | + <label htmlFor="foreground" className="colorInput"> |
| 25 | + Foreground Color: |
| 26 | + <input |
| 27 | + type="color" |
| 28 | + id="foreground" |
| 29 | + value={foreground} |
| 30 | + onChange={handleForegroundChange} |
| 31 | + /> |
| 32 | + </label> |
| 33 | + |
| 34 | + <label htmlFor="background" className="colorInput"> |
| 35 | + Background Color: |
| 36 | + <input |
| 37 | + type="color" |
| 38 | + id="background" |
| 39 | + value={background} |
| 40 | + onChange={handleBackgroundChange} |
| 41 | + /> |
| 42 | + </label> |
| 43 | + |
| 44 | + <div id="result" className={checkContrast()}> |
| 45 | + {checkContrast() === "pass" ? "Pass" : "Fail"} |
| 46 | + </div> |
| 47 | + </div> |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +function getContrastRatio(foreground, background) { |
| 52 | + const lum1 = getRelativeLuminance(parseHexColor(foreground)); |
| 53 | + const lum2 = getRelativeLuminance(parseHexColor(background)); |
| 54 | + |
| 55 | + return (Math.max(lum1, lum2) + 0.05) / (Math.min(lum1, lum2) + 0.05); |
| 56 | +} |
| 57 | + |
| 58 | +function parseHexColor(hex) { |
| 59 | + const bigint = parseInt(hex.substring(1), 16); |
| 60 | + const r = (bigint >> 16) & 255; |
| 61 | + const g = (bigint >> 8) & 255; |
| 62 | + const b = bigint & 255; |
| 63 | + |
| 64 | + return { r, g, b }; |
| 65 | +} |
| 66 | + |
| 67 | +function getRelativeLuminance(color) { |
| 68 | + const { r, g, b } = color; |
| 69 | + |
| 70 | + const rsrgb = r / 255; |
| 71 | + const gsrgb = g / 255; |
| 72 | + const bsrgb = b / 255; |
| 73 | + |
| 74 | + const rlinear = |
| 75 | + rsrgb <= 0.03928 ? rsrgb / 12.92 : ((rsrgb + 0.055) / 1.055) ** 2.4; |
| 76 | + const glinear = |
| 77 | + gsrgb <= 0.03928 ? gsrgb / 12.92 : ((gsrgb + 0.055) / 1.055) ** 2.4; |
| 78 | + const blinear = |
| 79 | + bsrgb <= 0.03928 ? bsrgb / 12.92 : ((bsrgb + 0.055) / 1.055) ** 2.4; |
| 80 | + |
| 81 | + return 0.2126 * rlinear + 0.7152 * glinear + 0.0722 * blinear; |
| 82 | +} |
| 83 | + |
| 84 | +ReactDOM.render(<ContrastChecker />, document.getElementById("app")); |
0 commit comments