election map coloring

This commit is contained in:
mantikoros 2022-10-05 16:57:01 -05:00
parent 0818a94307
commit 60aa294131
2 changed files with 27 additions and 4 deletions

24
common/util/color.ts Normal file
View File

@ -0,0 +1,24 @@
export const interpolateColor = (color1: string, color2: string, p: number) => {
const rgb1 = parseInt(color1.replace('#', ''), 16)
const rgb2 = parseInt(color2.replace('#', ''), 16)
const [r1, g1, b1] = toArray(rgb1)
const [r2, g2, b2] = toArray(rgb2)
const q = 1 - p
const rr = Math.round(r1 * q + r2 * p)
const rg = Math.round(g1 * q + g2 * p)
const rb = Math.round(b1 * q + b2 * p)
const hexString = Number((rr << 16) + (rg << 8) + rb).toString(16)
const hex = `#${'0'.repeat(6 - hexString.length)}${hexString}`
return hex
}
function toArray(rgb: number) {
const r = rgb >> 16
const g = (rgb >> 8) % 256
const b = rgb % 256
return [r, g, b]
}

View File

@ -9,6 +9,7 @@ import {
getContractFromSlug,
listenForContract,
} from 'web/lib/firebase/contracts'
import { interpolateColor } from 'common/util/color'
export interface StateElectionMarket {
creatorUsername: string
@ -45,10 +46,8 @@ export function StateElectionMap(props: { markets: StateElectionMarket[] }) {
const probToColor = (prob: number, isWinRepublican: boolean) => {
const p = isWinRepublican ? prob : 1 - prob
const hue = p > 0.5 ? 350 : 240
const saturation = 100
const lightness = 100 - 50 * Math.abs(p - 0.5)
return `hsl(${hue}, ${saturation}%, ${lightness}%)`
const color = p > 0.5 ? '#e4534b' : '#5f6eb0'
return interpolateColor('#ebe4ec', color, Math.abs(p - 0.5) * 2)
}
const useContracts = (slugs: string[]) => {