JavaScript `colorFromTo` Helper Function

In this example below you will see how to do a JavaScript `colorFromTo` Helper Function with some HTML / CSS and Javascript

JavaScript fromTo Helper FunctionGets the colors between a and b. Supports rgba values (test #2). Click on a color to get a prompt to copy the color.

Thumbnail
This awesome code was written by 0x04, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 0x04 ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>JavaScript `colorFromTo` Helper Function</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <h1>JavaScript `colorFromTo` Helper Function</h1>
<p>Gets the colors between `a` and `b`. Supports rgba values (test #2). Click on a color to get a prompt to copy the color.</p>
<p>
  <a href="#test1">test #1</a>
  <a href="#test2">test #2</a>
  <a href="#test3">test #3</a>
  <a href="#test4">test #4</a>
  <a href="#test5">test #5 (randomizer on board!)</a>
</p>
<h2 id="test2">test #1:</h2>
<div class="cl-test cl-test-1"></div>
<h2 id="test2">test #2:</h2>
<div class="cl-test cl-test-2"></div>
<h2 id="test3">test #3:</h2>
<div class="cl-test cl-test-3"></div>
<h2 id="test4">test #4:</h2>
<div class="cl-test cl-test-4"></div>
<h2 id="test5">test #5 <button onclick="randomize()">randomize!</button>:</h2>
<div class="cl-test cl-test-5"></div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/0x04/javascript-colorfromto-helper-function-tbrHx */
body
{
  background: linear-gradient(
      45deg,
      #333 25%,
      #222 25%,
      #222 50%,
      #222 50%,
      #333 50%,
      #333 75%,
      #222 75%
  );
  /*
  Psssst: I will tell you a "little dirty secret",
  this values must be a power of 2 due sub pixel
  rendering (for a gradient that's rotated e.g.).
  */
  background-size: 64px 64px;
  padding: 10px;
  font-family: monospace;
  color: white;
}

a
{
  color: white;
}

.cl
{
  padding: 5px;
}

.cl-test
{
  border-radius: 16px;
  overflow: hidden;
}

/*Downloaded from https://www.codeseek.co/0x04/javascript-colorfromto-helper-function-tbrHx */
// @license MIT
// @credits would be nice ^^ (@0x04)
function colorFromTo(a, b, steps, asHex)
{
  var _gi = '[colorFromTo] a: [ ' + a + ' ], b: [ ' + b + ' ] steps: ' + steps + ' asHex: ' + asHex;
  console.group(_gi);
  
  var result = [],
      diff = [],
      i, l = Math.min(a.length, b.length);

  for (i = 0; i < l; i++)
  {
    diff.push(a[i] - b[i]);
  }

  for (var step = 0; step < steps + 1; step++)
  {
    var amount = step / steps,
        rgb = [],
        hex = 0x0;

    for (i = 0; i < l; i++)
    {
      var dec = a[i] - diff[i] * amount;
      // red, green, blue
      if (i < 3)
      {
        dec = Math.round(dec);
        hex += dec << (2 - i) * 8;
      }
      // alpha
      else dec = Math.round(dec * 100) / 100;
      rgb.push(dec);
    }

    result.push(asHex ? hex : rgb);

    console.log(
      '%s/%s: [ %s ] #%s',
      step,
      steps,
      rgb.join(', '),
      hex.toString(16)
    );
  }
  
  console.groupEnd(_gi);
  
  return result;
}

//------------------------------------------------------------------------------

var steps = 25;
var elementCount = 1;
var elementSelector = '.cl-test-%s';

function getElement()
{
  return document.querySelector(elementSelector.replace('%s', elementCount));
}

function createElement(v, i)
{
  var e = document.createElement('div');
  var color;

  if (Array.isArray(v))
  {
    color = (v.length == 4 ? 'rgba(%s)' : 'rbg(%s)').replace('%s', v.join(','));
  }
  else
  {
    color = v.toString(16).split(/|/);
    
    // Zerofill
    for (var i = color.length; i < 6; i++)
    {
      color.unshift('0');
    }

    color = '#' + color.join('');
  }

  e.classList.add('cl');
  // invert color
  //e.style.color = '#' + (0xFFFFFF - v).toString(16);
  e.style.backgroundColor = color;
  e.title = color;
  getElement().appendChild(e);
}  

//------------------------------------------------------------------------------

// test #1
colorFromTo(
  [ 0xff, 0xff, 0xff ],
  [ 0x00, 0x00, 0x00 ],
  steps,
  true
).forEach(createElement);

elementCount++;

// test #2
colorFromTo(
  [ 0x00, 0x00, 0x00, 0 ],
  [ 0xff, 0xff, 0xff, 1 ],
  steps,
  false
).forEach(createElement);

elementCount++;

// test #3
colorFromTo(
  [ 0x00, 0x77, 0xff ],
  [ 0xff, 0x77, 0x00 ],
  steps,
  true
).forEach(createElement);

elementCount++;

// test #4
colorFromTo(
  [ 0xff, 0x00, 0xff ],
  [ 0x00, 0xff, 0x00 ],
  steps,
  true
).forEach(createElement);

elementCount++;

function randomize()
{
  getElement().innerHTML = '';

  // test #5
  var r1 = [];
  var r2 = [];

  for (var i = 2; i > -1; i--)
  {
    r1.push(Math.round(Math.random() * 0xFF));
    r2.push(Math.round(Math.random() * 0xFF));
  }

  r1.push(Math.round(Math.random() * 100) / 100);
  r2.push(Math.round(Math.random() * 100) / 100);

  colorFromTo(
    r1,
    r2,
    steps,
    false
  ).forEach(createElement);
}

randomize();

document.body.addEventListener('click', function(event)
{
  if (event.target.classList.contains('cl'))
  {
    prompt('Copy if you want:', event.target.title);
  }
});

Comments