Skip to content

Commit

Permalink
Add calculate new color function
Browse files Browse the repository at this point in the history
  • Loading branch information
ozgrozer committed Jun 30, 2024
1 parent f3de69c commit 8f59eb7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
6 changes: 4 additions & 2 deletions components/NewColorButtons.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import clx from '@functions/clx'
import styles from '@styles/Colors.module.scss'
import { useAppContext } from '@contexts/AppContext'
import calculateNewColor from '@functions/calculateNewColor'

const NewColorButton = ({ index }) => {
const { setState } = useAppContext()

const buttonOnClick = () => {
setState(prevState => {
setState((prevState) => {
const newColors = [...prevState.colors]
newColors.splice(index, 0, '#1BB0CE')
const newColor = calculateNewColor(prevState.colors, index)
newColors.splice(index, 0, newColor)
return {
...prevState,
colors: newColors
Expand Down
30 changes: 30 additions & 0 deletions functions/calculateNewColor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export default (colors, index) => {
const hexToRgb = hex => {
const bigint = parseInt(hex.slice(1), 16)
return [(bigint >> 16) & 255, (bigint >> 8) & 255, bigint & 255]
}

const rgbToHex = rgb =>
'#' + rgb.map(x => x.toString(16).padStart(2, '0')).join('')

const averageColor = (color1, color2) => {
const rgb1 = hexToRgb(color1)
const rgb2 = hexToRgb(color2)
return rgb1.map((value, i) => Math.round((value + rgb2[i]) / 2))
}

const shiftColor = color => {
const rgb = hexToRgb(color)
return rgb.map(value =>
Math.min(255, Math.max(0, value + Math.floor(Math.random() * 61) - 30))
)
}

if (index === 0) {
return rgbToHex(shiftColor(colors[0]))
} else if (index === colors.length) {
return rgbToHex(shiftColor(colors[colors.length - 1]))
} else {
return rgbToHex(averageColor(colors[index - 1], colors[index]))
}
}

0 comments on commit 8f59eb7

Please sign in to comment.