Skip to content

Instantly share code, notes, and snippets.

@irlabs
Last active September 4, 2020 14:43
Show Gist options
  • Save irlabs/7df8f893a3dab01e06fd4c5250aabe92 to your computer and use it in GitHub Desktop.
Save irlabs/7df8f893a3dab01e06fd4c5250aabe92 to your computer and use it in GitHub Desktop.
Contrast Color
<html>
<head>
</head>
<body>
<div class="wrap">
<h1 class="title">Contrast Color</h1>
<div id="palette"></div>
</div>
</body>
</html>
// c is a tiny color object
function contrast_color(c) {
let dark = "#000"
let light = "#fff"
let hsv = c.toHsv()
let stops = [
{h: 0, s: 1.0},
{h: 30, s: 0.4},
{h: 45, s: 0.2},
{h: 60, s: 0.1},
{h: 90, s: 0.2},
{h: 120, s: 0.5},
{h: 135, s: 0.55},
{h: 180, s: 0.4},
{h: 215, s: 0.8},
{h: 240, s: 1.6},
{h: 300, s: 0.8},
{h: 360, s: 1.0},
]
for (let i = 0; i < stops.length - 1; i++) {
let stop = stops[i]
let next = stops[i + 1]
if (hsv.h < next.h) {
let ds = next.s - stop.s
let h = (hsv.h - stop.h) / (next.h - stop.h)
let linear = h * ds
return ((-hsv.s * (stop.s + (h * ds))) + hsv.v > 0.5) ? dark : light
}
}
// Default
return (hsv.v > 0.5) ? dark : light
}
var satSlider = 1.0
var gridContent = ""
for (let val = -100; val < 100; val += 5) {
gridContent += '<div class="row">'
for (let hue = 0; hue < 360; hue += 5) {
let sat = (val < 0 ? 100 + val : 100) * satSlider
let v = val > 0 ? 100 - val : 100
let col = tinycolor({ h: hue, s: sat, v: v })
let concol = contrast_color(col)
gridContent += '<span class="swatch" style="background-color: ' + col.toHexString() + '"><div class="inner" style="color: ' + concol + '">&bull;</div></span>'
}
gridContent += '</div>'
}
palette.innerHTML = gridContent
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinycolor/1.4.1/tinycolor.min.js"></script>
body {
color: #fff;
background: #171F30;
line-height: 150%;
}
.wrap {
min-height: 100vh;
max-width: 840px;
margin: 0 auto;
/* display: flex;
flex-direction: row; */
align-items: center;
justify-content: center;
.half {
width: 50%;
padding: 32px 0;
}
}
.title {
font-family: sans-serif;
line-height: 24px;
display: block;
padding: 8px 0;
}
.readout {
margin-top: 32px;
line-height: 180%;
}
#palette {
display: block;
}
.swatch {
width: 10px;
height: 10px;
display: inline-block;
}
.inner {
font-size: 80%;
margin-top: -6px;
margin-left: 3px;
}
.row {
height: 10px;
display: block;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment