Skip to content

Commit

Permalink
Colour scale can have values > 100%
Browse files Browse the repository at this point in the history
  • Loading branch information
slowe committed Apr 4, 2024
1 parent 23bd0ec commit a43cc2c
Showing 1 changed file with 42 additions and 21 deletions.
63 changes: 42 additions & 21 deletions lib/colour/colour-scale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ export function ColourScale(gradient: string): ColourScale {
const max = 1;
if(namedColourScales[gradient]) gradient = namedColourScales[gradient];
const stops = extractColours(gradient);
let maxidx = stops.length-1;
for(let i = 0; i < stops.length ; i++){
if(stops[i].v == 100){
maxidx = i;
i = stops.length;
}
}

function getColour(v: number) {
const v2 = 100 * (v - min) / (max - min);
Expand All @@ -109,30 +116,44 @@ export function ColourScale(gradient: string): ColourScale {
"alpha": parseFloat((v2 / 100).toFixed(3)),
};
} else {
if(v > max){
if(v == max){
cfinal = {
"r": stops[stops.length-1].c.rgb[0],
"g": stops[stops.length-1].c.rgb[1],
"b": stops[stops.length-1].c.rgb[2],
"alpha": stops[stops.length-1].c.alpha,
};
}else if(v == max){
// If the last two stops are both 100 we will use the first of them
let j = (stops[stops.length-1].v==100 && stops[stops.length-2].v==100) ? stops.length-2 : stops.length-1;
cfinal = {
"r": stops[j].c.rgb[0],
"g": stops[j].c.rgb[1],
"b": stops[j].c.rgb[2],
"alpha": stops[j].c.alpha,
"r": stops[maxidx].c.rgb[0],
"g": stops[maxidx].c.rgb[1],
"b": stops[maxidx].c.rgb[2],
"alpha": stops[maxidx].c.alpha,
};
}else{
for (let c = 0; c < stops.length - 1; c++) {
if (v2 >= stops[c].v && v2 <= stops[c + 1].v) {
// On this colour stop
let pc = 100 * (v2 - stops[c].v) / (stops[c + 1].v - stops[c].v);
if (pc > 100) pc = 100; // Don't go above colour range (shouldn't be if here)
cfinal = getColourPercent(pc, stops[c].c, stops[c + 1].c);
continue;
// Is the value greater than our scale?
if(v2 > stops[stops.length-1].v){
let j = stops.length-1;
cfinal = {
"r": stops[j].c.rgb[0],
"g": stops[j].c.rgb[1],
"b": stops[j].c.rgb[2],
"alpha": stops[j].c.alpha,
}
}else{
for (let c = 0; c < stops.length - 1; c++) {
if (v2 >= stops[c].v){
if (c < stops.length-1){
if (v2 <= stops[c + 1].v) {
// On this colour stop
let pc = 100 * (v2 - stops[c].v) / (stops[c + 1].v - stops[c].v);
cfinal = getColourPercent(pc, stops[c].c, stops[c + 1].c);
continue;
}
} else {
let j = stops.length-1;
cfinal = {
"r": stops[j].c.rgb[0],
"g": stops[j].c.rgb[1],
"b": stops[j].c.rgb[2],
"alpha": stops[j].c.alpha,
}
continue;
}
}
}
}
}
Expand Down

0 comments on commit a43cc2c

Please sign in to comment.