Last active
July 26, 2023 20:25
-
-
Save myersjustinc/ac9073c57d25bdb7a126fb4b81a769e3 to your computer and use it in GitHub Desktop.
Interpolate colors in LAB space
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
'use strict' | |
// DEPENDENCIES --------------------------------------------------------------- | |
import { argv, exit } from 'node:process' | |
import { rgb } from 'd3-color' | |
import { interpolateLab, piecewise } from 'd3-interpolate' | |
import { range } from 'd3-array' | |
// ARGUMENTS ------------------------------------------------------------------ | |
let [ minColor, midColor, maxColor, classCountRaw ] = argv.slice(2) | |
if ( classCountRaw == null ) { | |
classCountRaw = maxColor | |
maxColor = midColor | |
midColor = null | |
} | |
const classCount = parseInt(classCountRaw, 10) | |
const anyRequiredArgIsNull = ( | |
minColor == null || maxColor == null || classCountRaw == null) | |
const classCountIsNotInt = classCount !== parseFloat(classCountRaw) | |
if ( anyRequiredArgIsNull || classCountIsNotInt ) { | |
console.error( | |
`Usage: ${argv[1]} MIN_COLOR [MID_COLOR] MAX_COLOR CLASS_COUNT`) | |
exit(1) | |
} | |
// INTERPOLATION -------------------------------------------------------------- | |
const interpolator = (function() { | |
if ( midColor == null ) { | |
return interpolateLab(minColor, maxColor) | |
} | |
return piecewise(interpolateLab, [minColor, midColor, maxColor]) | |
})(); | |
const colors = range(classCount).map(function(i) { | |
return rgb(interpolator(i / (classCount - 1))).hex() | |
}) | |
// OUTPUT --------------------------------------------------------------------- | |
console.log(JSON.stringify(colors, null, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment