Intro to lerp: render gradient rectangles on canvas

by johnsonjo4531

HTML

<canvas width="1000px" height="1000px" id="canvas" style="width: 100vw; height: 100vh;"/>

CSS

html, body {
margin: 0;
padding: 0;
max-height: 100vh;
max-width: 100vw;
overflow: hidden;
}

JavaScript

/** lerp two scalars/numbers
 * @param v0 the number to start the lerp from
 * @param v1 the number to lerp towards
 * @param t the percentage of the lerp a number from 0 - 1
 */
function lerp(v0, v1, t) {
  return v0 + t * (v1 - v0);
}

let canvas = document.getElementById("canvas");


let ctx = canvas.getContext("2d");
// Change this number lower and higher then click run up above!
let totalRects = 20;


let color1 = [0, 0, 255];
let color2 = [255, 0, 0];

let maxCanvasWidth = canvas.width;
let maxCanvasHeight = canvas.height;

for(let i = 0; i <= totalRects; ++i) {
  ctx.fillStyle = `rgb(${
    lerp(color1[0], color2[0], i / totalRects)
    }, ${
    lerp(color1[1], color2[1], i / totalRects)
    }, ${
    lerp(color1[2], color2[2], i / totalRects)
    })`;
  ctx.fillRect(lerp(0, maxCanvasWidth, i / totalRects), 0, maxCanvasWidth / totalRects, maxCanvasHeight);
  // ctx.fillRect()
}
ctx.stroke();