threejs wave loop rendering in typescript

To create an animation loop of a wave using Three.js in TypeScript, you can follow these steps:

  1. Install Three.js and its types for TypeScript
index.ts
npm install three @types/three
31 chars
2 lines
  1. Create a new Three.js scene, camera and renderer
index.ts
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
314 chars
8 lines
  1. Create a geometry for the wave surface and a material with a wave-like texture
index.ts
const geometry = new THREE.PlaneGeometry(100, 100, 50, 50);
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/wave_texture.jpg');
const material = new THREE.MeshBasicMaterial({map: texture});
235 chars
5 lines
  1. Create a mesh for the wave surface and add it to the scene
index.ts
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
66 chars
3 lines
  1. Define a function to update the wave animation frame by frame
index.ts
function updateWaveAnimation() {
  const time = performance.now() / 2000; // change the divisor to adjust the animation speed
  const positionArray = geometry.attributes.position.array as Float32Array;
  
  for (let i = 0; i < positionArray.length; i += 3) {
    const x = positionArray[i];
    const y = positionArray[i + 1];
    const z = Math.sin(x / 5 + time) * Math.cos(y / 5 + time) * 2;
    
    positionArray[i + 2] = z;
  }
  
  geometry.attributes.position.needsUpdate = true;
}
489 chars
15 lines
  1. Create a loop function to render the scene and update the wave animation every frame
index.ts
function renderLoop() {
  requestAnimationFrame(renderLoop);
  
  updateWaveAnimation();
  
  renderer.render(scene, camera);
}
renderLoop();
142 chars
9 lines

You can tweak the parameters of the wave animation to achieve different effects, such as changing the amplitude, frequency or propagation direction.

gistlibby LogSnag