javascriptkeyframeeasingjquery-easingeasing-functions

Imitating @keyframes rule using Javascript only


I'm trying to create a function that uses percentage to get a number. The idea is to have something like this: 0%: 100px 50%: 200px 75%: 210px

So when I run my function at a percentage like 25% it blends 0 and 50 together, same for above 50%.

It sounds kind of complicated, the overall idea is to create something using JS only that will ease the numbers going from 0 to 100%

I've tried using regular percentage calculation, yet it doesn't really work for 3 or more variables.


Solution

  • So if you don't mind I've taken the liberty of turning your percentage into a JSON object:

    let input = {
      0: 100,
      50: 200,
      75: 210,
    };
    

    We can then do something like this if we assume percentages are always whole numbers:

    let output = {};
    let previous = null;
    // for each whole percent
    for(let keyPercent in input)
    {
      // cast to number
      let currPercent = parseFloat(keyPercent);
      // get value of percent
      let currValue = input[currPercent];
      if (currValue != null) { // if value is present
        if (previous != null) { // and previous value is not null
          // find the step size (valDiff) / (percentDiff)
          let step = (currValue - previous.value) / (currPercent - previous.percent);
          // count to multiply by step
          let count = 0;
          // this produces the percent value for every step between previous.percent and currPercent
          for (let prevPercent = previous.percent; prevPercent <= currPercent; prevPercent += 1) {
            output[prevPercent] = previous.value + (step * count);
            count += 1;
          }
        }
        // set previous value
        previous = { percent: currPercent, value: currValue };
      }
    }
    console.log(output);
    

    this outputs something along the lines of:

    0: 100
    1: 102
    2: 104
    ...
    48: 196
    49: 198
    50: 200
    51: 200.4
    52: 200.8
    ...
    73: 209.2
    74: 209.6
    75: 210
    

    Let me know if you need any clarification.

    Note: comments are made in code