Skip to content

Commit

Permalink
add examples to ColorSequence
Browse files Browse the repository at this point in the history
  • Loading branch information
ericyd committed Jan 8, 2024
1 parent 6ac20f0 commit c4182b2
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/color/color-sequence.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@ import { ColorRgb } from './rgb.js'
* @typedef {[number, ColorRgb]} ColorStop
*/

/**
* @description A sequence of colors that can be linearly interpolated together.
* @example
* const spectrum = ColorSequence.fromHexes(['#ff0000', '#00ff00', '#0000ff'])
* spectrum.at(0) // ColorRgb { r: 1, g: 0, b: 0, a: 1 }
* spectrum.at(0.5) // ColorRgb { r: 0, g: 1, b: 0, a: 1 }
* spectrum.at(1) // ColorRgb { r: 0, g: 0, b: 1, a: 1 }
* @example
* // You may customize the "stops" as needed
* // Note that you must pass ColorRgb instances in the ColorStop pairs,
* // rather than simple hex strings
* const spectrum = new ColorSequence([
* [0, ColorRgb.fromHex('#ff0000')],
* [0.7, ColorRgb.fromHex('#00ff00')],
* [1, ColorRgb.fromHex('#0000ff')]
* ])
* spectrum.at(0) // ColorRgb { r: 1, g: 0, b: 0, a: 1 }
* spectrum.at(0.5) // ColorRgb { r: 0.5714285714285714, g: 1, b: 0, a: 1 }
* spectrum.at(0.7) // ColorRgb { r: 0, g: 1, b: 0, a: 1 }
* spectrum.at(1) // ColorRgb { r: 0, g: 0, b: 1, a: 1 }
*/
export class ColorSequence {
/** @type {ColorStop[]} */
#pairs = []
Expand Down Expand Up @@ -41,8 +62,6 @@ export class ColorSequence {
*/
at(t) {
const stopB = this.#pairs.findIndex(([stopVal]) => stopVal >= t)
// console.log(this.#pairs)
console.log({ stopB })
if (stopB === 0 || this.#pairs.length === 1) {
return this.#pairs[stopB][1]
}
Expand All @@ -52,7 +71,6 @@ export class ColorSequence {
const stopA = stopB - 1
const range = this.#pairs[stopB][0] - this.#pairs[stopA][0]
const percentage = (t - this.#pairs[stopA][0]) / range
console.log({ range, percentage })
return this.#pairs[stopA][1].mix(this.#pairs[stopB][1], percentage)
}
}

0 comments on commit c4182b2

Please sign in to comment.