Gradient Generator Test

by rexonms

HTML

<div id="container">
  <div id="swatches-sample">  
  </div>
  <h4>Swatches</h4>
  <div id="swatches">
  </div>
</div>

CSS

body {
  font-family:Arial, Helvetica, sans-serif;
  color: #333;
}
h4 {
  margin-bottom: 5px;
}

#swatches {
 background: #fff;
 min-height:100px;
 min-width: 300px;
 display: flex;
 justify-content: flex-start;
}

.swatch {
  min-height: 50px;
  min-width: 50px;
  background: #ccc;
  margin-right: 1px;
  text-align:center;
  font-size: 12px;
  line-height: 12px;
  color: #fff;
  display: flex;
  justify-content: center;
  text-align: center;
  align-items: center;
}

JavaScript

const steps = 5
const startColor = {
    r: 1,
    g: 32,
    b: 80,
    a: 1
}
const endColor = {
    r: 6,
    g: 74,
    b: 207,
    a: 1
}


let gradinets = getGradients(startColor, endColor, steps)
//console.log(gradinets)
displayGradients(gradinets)

/*
 * Returns gradient based on the start and end rgba value
 * @param startColor { r:17, g:17, b:21, a: 1 }
 * @param endColor  { r:0, g:182, b:207, a: 1}
 * @param count    10
 * return ["rgba(2,40,105,1)", "rgba(3,49,131,1)", "rgba(4,57,156,1)", "rgba(5,66,182,1)", "rgba(6,74,207,1)"]
 */
function getGradients(startColor, endColor, count) {

    const {
        r: startRed,
        g: startGreen,
        b: startBlue,
        a: startAlpha
    } = startColor;
    const {
        r: endRed,
        g: endGreen,
        b: endBlue,
        a: endAlpha
    } = endColor;

    const redValues = buildColor(startRed, endRed, count);
    const greenValues = buildColor(startGreen, endGreen, count);
    const blueValues = buildColor(startBlue, endBlue, count);
    const alphaValues = buildColor(startAlpha, endAlpha, count);
    const colors = [];

    // At this stage all the array elements will be of same length.
    for (let i = 0; i < redValues.length; i++) {
        const red = redValues[i];
        const green = greenValues[i];
        const blue = blueValues[i];
        const alpha = alphaValues[i];

        colors.push(`rgba(${red},${green},${blue},${alpha})`);
    }
    /* return ["rgba(2,40,105,1)", "rgba(3,49,131,1)", "rgba(4,57,156,1)", "rgba(5,66,182,1)", "rgba(6,74,207,1)"] */

    return colors;

}

function buildColor(startColVal, endColVal, count) {
    const diffRed = Math.abs(endColVal - startColVal);
    const step = diffRed / count;

    const result = [];

    for (let i = startColVal; i < endColVal; i = i + step) {
        result.push(i);
    }

    return result;
}

/**
 * Injects the gradinet watches to the UI 
 */
function displayGradients(gradinets) {
    let swatchesDiv =...