Color interpolation

by Raul Bojalil

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var timer = 0;

function colorInterpolate(colorA, colorB, intval) {

	function getRgb(color) {
  let [r, g, b] = color.replace('rgb(', '')
    .replace(')', '')
    .split(',')
    .map(str => Number(str));;
  return {
    r,
    g,
    b
  }
}

  const rgbA = getRgb(colorA),
    rgbB = getRgb(colorB);
  const colorVal = (prop) =>
    Math.round(rgbA[prop] * (1 - intval) + rgbB[prop] * intval);
  return "rgb(" + colorVal('r') + "," + colorVal('g') + "," + colorVal('b') + ")";
}


function draw(diff) {

  if (diff < 0 || isNaN(diff)) return;
  
  timer += diff * 0.001;
  
  //const color = colorInterpolate('rgb(255,0,0)', 'rgb(0,0,255)', 0.5);
  const color = colorInterpolate('rgb(255,0,0)', 'rgb(0,0,255)', Math.sin(timer));
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, 200, 200);
}

var startTime = window.mozAnimationStartTime || Date.now();

function animate(timestamp) {

  var drawStart = (timestamp || Date.now()),
      diff = drawStart - startTime;

  startTime = drawStart;

  requestAnimationFrame(animate);
  draw(diff);
}

animate();