Home > front end >  How to Use Negative Values in Lerp Function as Alpha Parameter
How to Use Negative Values in Lerp Function as Alpha Parameter

Time:10-07

I am trying to animate some text on the screen in two ways:

  1. Move its Y position from 1 to -1 [already finished]
  2. Shift its RGB color value from white(255,255,255) to green(149,184,6) [need help with]

I am using the Linear Interpolation function from enter image description here

This function will be used to get the alpha for the lerp function:

const r = Math.floor(lerp(255, 149, translate(positionY)));
const g = Math.floor(lerp(255, 184, translate(positionY)));
const b = Math.floor(lerp(255, 6, translate(positionY)));

CodePudding user response:

Ok so this linear stuff basically means that between 2 points there's only one line. So if you got 2 points right, then you got the right formula for all other points on the line.

So I started with [-1, 1] to [0, 1] transformation. It's clear to see that there should be /2 there because the range is double. But before we do I 'translate' it so that -1 will be equal 0 (and when I /2 it will stay 0).

Then I needed to reverse the 0 with 1 for the output, so I did a minus 1 for the result. Frankly I tried apply same logic but was too lazy.

Then I remembered I had an answer about that. It's a function that gets (x1,y1, x2, y2) and returns a linear function.

var x1 = -1;
var x2 = 1;

var y1 = 1;
var y2 = 0;

var calcY = getLinearFunction(x1, y1, x2, y2);
console.log(calcY(-1))
console.log(calcY(1))

function getLinearFunction(x1, y1, x2, y2) {
  var slope = (y2 - y1) / (x2 - x1);
  return function(x) {
    return slope * (x - x1)   y1;
  }
}

  • Related