From a43cc2c1cded17facbede097f9ae8589a7165d9f Mon Sep 17 00:00:00 2001 From: slowe <299787+slowe@users.noreply.github.com> Date: Thu, 4 Apr 2024 16:32:10 +0100 Subject: [PATCH] Colour scale can have values > 100% --- lib/colour/colour-scale.ts | 63 +++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/lib/colour/colour-scale.ts b/lib/colour/colour-scale.ts index 10fec9f..af19baa 100644 --- a/lib/colour/colour-scale.ts +++ b/lib/colour/colour-scale.ts @@ -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); @@ -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; + } + } } } }