Created
September 16, 2021 12:13
-
-
Save alex-boom/c5883023d2fa361403eb0aa213f156c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const hexToRgb = (hex, type = "string") => { | |
if (!hex) | |
{ | |
return false | |
} | |
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); | |
if (type === "string") | |
{ | |
return `${ parseInt(result[ 1 ], 16) }, ${ parseInt(result[ 2 ], 16) }, ${ parseInt(result[ 3 ], 16) }`; | |
} | |
return result ? { | |
r: parseInt(result[ 1 ], 16), | |
g: parseInt(result[ 2 ], 16), | |
b: parseInt(result[ 3 ], 16) | |
} : null; | |
}; | |
//Делает цвет фона, текста, темнее или светлее от основного цвета | |
// к примеру если основной цвет белый то функция преобразует этот цвет в ченрый и так т.д. | |
const lightOrDark = (hex) => { | |
const { r, g, b } = hexToRgb(hex, false); | |
// HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html | |
const hsp = Math.sqrt( | |
0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) | |
); | |
// Using the HSP value, determine whether the color is light or dark | |
return (hsp > 127.5) ? "black" : "white"; | |
} | |
const randomHex = () => { | |
let rand = Math.floor(Math.random() * 16777215).toString(16); | |
if (rand.length < 6) | |
{ | |
for (let i = 0, y = 6 - rand.length; i < y; i++) | |
{ | |
rand += "0"; | |
} | |
} | |
return rand; | |
}; | |
const hex = { | |
random: randomHex, | |
toRgb: hexToRgb, | |
lightOrDark | |
}; | |
export default hex; | |
//Работа функции пример lightOrDark в компоненте | |
import React, { useState } from "react"; | |
import { Button } from "antd"; | |
import hex from './utils/hex-color'; | |
const SetColor = () => { | |
const [ currentColor, setCurrentColor ] = useState('#000000'); | |
const lightOrDark = hex.lightOrDark(currentColor); | |
return ( | |
<div className=""> | |
<Button | |
style={ | |
{ | |
background: currentColor, | |
borderColor: lightOrDark, | |
color: lightOrDark, | |
} } | |
type="primary" | |
onClick={ () => setCurrentColor('#ffffff') } | |
> | |
Button text | |
</Button> | |
</div> | |
) | |
} | |
export default SetColor; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment