Untitled
let isString = value => typeof value === 'string' || value instanceof String; let hexToNum = value => Number("0x" + value); function gradientStep(startColor, endColor, index, max) { if(!isString(startColor) || !isString(endColor)) { throw "startColor and EndColor must be strings" } if(startColor.length != 6) { throw "startColor must be exactly 6 digits" } if(endColor.length != 6) { throw "endColor must be exactly 6 digits" } if(isNaN(hexToNum(startColor))) { throw "startColor must be valid hex" } if(isNaN(hexToNum(endColor))) { throw "startColor must be valid hex" } // Setup Stepping const step = 1 / max; const currentStepStart = step * index; const currentStepEnd = step * (index + 1); let start = startColor.match(/[0-9A-F]{2}/g).map(hexToNum); let end = endColor.match(/[0-9A-F]{2}/g).map(hexToNum); // Main Procssing Loop let startOutput = []; let endOutput = [] for(let colorIndex = 0; colorIndex < 3; colorIndex++) { let delta = end[colorIndex] - start[colorIndex]; startOutput[colorIndex] = Math.floor(currentStepStart * delta + start[colorIndex]) .toString(16) .padStart(2, '0'); endOutput[colorIndex] = Math.floor(currentStepEnd * delta + start[colorIndex]) .toString(16) .padStart(2, '0'); } return [startOutput.join(''), endOutput.join('')]; } let testMax = 5; let testStartColor = "FFFFFF"; let testEndColor = "FF0000"; for(let i = 0; i < testMax; i++) { [startHex, endHex] = gradientStep(testStartColor, testEndColor, i, testMax); console.log(startHex, endHex); } /* Example Output: ffffff ffcccc ffcccc ff9999 ff9999 ff6565 ff6565 ff3333 ff3333 ff0000 */
Leave a Comment