Skip to content

Instantly share code, notes, and snippets.

@myersjustinc
Last active July 26, 2023 20:25
Show Gist options
  • Save myersjustinc/ac9073c57d25bdb7a126fb4b81a769e3 to your computer and use it in GitHub Desktop.
Save myersjustinc/ac9073c57d25bdb7a126fb4b81a769e3 to your computer and use it in GitHub Desktop.
Interpolate colors in LAB space
'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