📜  lerp javascript (1)

📅  最后修改于: 2023-12-03 15:32:38.243000             🧑  作者: Mango

Lerp in JavaScript

Introduction

Lerp (linear interpolation) is a mathematical calculation used in computer graphics and animation to interpolate between two values. In JavaScript, you can use Lerp to interpolate between two numerical values at any given point in time.

Syntax
function lerp(start, end, amount) {
  return start + (end - start) * amount;
}
Usage

The lerp function takes three arguments:

  • start (number): The starting value.
  • end (number): The ending value.
  • amount (number): The amount to interpolate between start and end. This should be a value between 0 and 1.
const start = 0;
const end = 100;
const amount = 0.5;

const middleValue = lerp(start, end, amount); // 50

In the example above, the middleValue is calculated by interpolating start and end by amount which results in 50.

Real World Examples

Lerp can be useful in various animations and graphics applications, such as creating smooth transitions between two values, like fading in/out a UI element or animating a camera to follow an object.

// Example 1: Animate fading a DOM element in
const element = document.getElementById('example-element');
const startOpacity = 0;
const endOpacity = 1;
const duration = 1000; // ms

let elapsedTime = 0;
function animate() {
  const amount = elapsedTime / duration;
  const opacity = lerp(startOpacity, endOpacity, amount);
  element.style.opacity = opacity;

  if (elapsedTime < duration) {
    requestAnimationFrame(animate);
  }
  elapsedTime += 16; // Assuming 60 fps
}
animate();

// Example 2: Animate moving a camera to follow an object
const camera = new THREE.PerspectiveCamera(...);
const start = camera.position.clone();
const end = object.position.clone().add(new THREE.Vector3(0, 0, -10));
const duration = 1000; // ms

let elapsedTime = 0;
function animate() {
  const amount = elapsedTime / duration;
  const position = new THREE.Vector3(
    lerp(start.x, end.x, amount),
    lerp(start.y, end.y, amount),
    lerp(start.z, end.z, amount)
  );
  camera.position.copy(position);

  if (elapsedTime < duration) {
    requestAnimationFrame(animate);
  }
  elapsedTime += 16; // Assuming 60 fps
}
animate();
Conclusion

Lerp is a simple yet powerful tool to interpolate between two values in JavaScript. It can be used in various applications such as animations and graphics to create smooth transitions and movements. With the syntax and examples provided, you can now apply Lerp to your code and create stunning visual effects!