Last active
September 9, 2024 09:33
-
-
Save andyj/0b0f34c998a397603c020424bed37d8f to your computer and use it in GitHub Desktop.
Revisions
-
andyj revised this gist
Sep 9, 2024 . No changes.There are no files selected for viewing
-
andyj created this gist
Sep 9, 2024 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ /** * Calculates a colour based on the current value, relative to a given range (minValue to maxValue). * The hue is calculated in HSL format, transitioning from Green (at high values) to Red (at low values). * * @param {number} currentValue - The current value for which the colour is calculated. * @param {number} minValue - The minimum value of the range. * @param {number} maxValue - The maximum value of the range. * @returns {string} - The calculated HSL colour as a string (e.g., "hsl(120, 100%, 80%)"). */ function calculateColor(currentValue, minValue, maxValue) { // Ensure minValue is not greater than maxValue if (minValue >= maxValue) { return "hsl(0, 0%, 100%)"; // Default to white if range is invalid } // Normalise the current value to a 0-1 scale let range = maxValue - minValue; let normalisedValue = (currentValue - minValue) / range; // Reverse the hue calculation to go from Green to Red // Green (120 hue) at high values, Red (0 hue) at low values let hue = normalisedValue * 120; // Normalized hue now goes from green (120) to red (0) // Saturation and lightness can be adjusted for desired effect let saturation = 100; // Full saturation for vibrant colours let lightness = 80; // Mid-lightness for balanced colours // Return the HSL colour in CSS format return "hsl(" + hue + "," + saturation + "%," + lightness + "%)"; }