screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState, useEffect } = React function App() { const colors = ['#9FA8DA', '#7986CB', '#448AFF', '#26A69A', '#81C784', '#69F0AE', '#B9F6CA', '#558B2F', '#827717']; return ( <div class='container'> <h3>React Js Change Text Color Based On Brightness Background</h3> {colors.map((color, index) => ( <div className='color-div' key={index} style={{ backgroundColor: color }}> <ColorText background={color} /> </div> ))} </div> ); }; const ColorText = ({ background }) => { const [textColor, setTextColor] = useState('black'); useEffect(() => { const calculateBrightness = (color) => { const hex = color.replace('#', ''); const r = parseInt(hex.substring(0, 2), 16); const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); const brightness = (r * 299 + g * 587 + b * 114) / 1000; return brightness; }; const isDarkBackground = calculateBrightness(background) < 128; const newTextColor = isDarkBackground ? 'white' : 'black'; setTextColor(newTextColor); }, [background]); return <h2 style={{ color: textColor }}>{background}</h2>; } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .container { width: 600px; margin: 0 auto; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); padding: 20px; text-align: center; display: flex; flex-wrap: wrap; justify-content: center; } .color-div { width: 150px; height: 150px; margin: 10px; display: flex; align-items: center; justify-content: center; border-radius: 50%; color: white; font-size: 18px; font-weight: bold; text-transform: uppercase; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16); } .color-div:hover { transform: scale(1.05); box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.16); cursor: pointer; } </style> </body> </html>