How can we cycle through multiple colors using lerp in Three.js?

I am currently engaged in a project using the Three.JS Online Editor. The main goal of my project is to create a Day/Night Cycle that loops through various colors to set the scene background. The cycle should include:

  1. Day
  2. Sunrise/Sunset
  3. Night
  4. Sunrise/Sunset
  5. Day ... And so on.

The loop should continue indefinitely. So far, I have managed to loop through two colors successfully, but I am having difficulty looping through all three colors. Is there a solution for achieving this?

Displayed below is the current state of my code:

//var day = new THREE.Color(0xB8F4FF);
//var duskdawn = new THREE.Color(0xFF571F);
//var night = new THREE.Color(0x17012D);

//scene.background = new THREE.Color(0xB8F4FF);

let t = 0;
let tn = 0;
let cyc = 0;

//const day = new THREE.Color(0xB8F4FF);
var day = new THREE.Color(0xB8F4FF);
const duskdawn = new THREE.Color(0xFF571F);
const night = new THREE.Color(0x17012D);

animate();

function animate() {

  requestAnimationFrame(animate);
  t += 0.01;
  tn += 0.01;
  cyc = 0.9;
  cyc += 0.1;
  if(cyc % 2 == 1){
      //day = new THREE.Color(0x17012D);
      day = new THREE.Color(0xB8F4FF);
      //scene.background.copy(day).lerp(duskdawn, 0.5 * (Math.sin(t) + 1));
      scene.background.copy(day).lerp(duskdawn, 0.5 * (Math.sin(t) + 1));
      day = new THREE.Color(0x17012D);
      cyc += 0.1;
      if(cyc != 1){
          day = new THREE.Color(0x17012D);
      }
  /**/
  }
  if(cyc % 2 != 0){
      //scene.background.copy(night).lerp(duskdawn, 0.5 * (Math.sin(tn) + 1));
      //day = new THREE.Color(0xB8F4FF);
      day = new THREE.Color(0x17012D);
      scene.background.copy(day).lerp(duskdawn, 0.5 * (Math.sin(tn) + 1));
      //day = new THREE.Color(0xB8F4FF);
      cyc += 0.1;
      //cyc = 0;
  }
  /**/
  cyc = 0.9;
  cyc += 0.1;
  //cyc += 1;
}

I would greatly appreciate any assistance with this issue. If more information is required, please feel free to reach out. Thank you!

Answer №1

Follow this approach:

let camera, scene, renderer, clock;

const colors = [
  new THREE.Color(0xff0000),
  new THREE.Color(0xffff00),
  new THREE.Color(0x00ff00),
  new THREE.Color(0x0000ff)
];

const duration = 4; // 4s

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 1;

  scene = new THREE.Scene();
  scene.background = new THREE.Color();

  clock = new THREE.Clock();

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

  const time = clock.getElapsedTime();

  animateBackground(time)

  renderer.render(scene, camera);

}

function animateBackground(t) {

  const f = Math.floor(duration / colors.length);
  const i1 = Math.floor((t / f) % colors.length);
  let i2 = i1 + 1;

  if (i2 === colors.length) i2 = 0;

  const color1 = colors[i1];
  const color2 = colors[i2];
  const a = (t / f) % colors.length % 1;

  scene.background.copy(color1);
  scene.background.lerp(color2, a);


}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2f33293e3e1b6b756a696f">[email protected]</a>/build/three.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

Choosing a sequence of text snippets divided by the <br> tag found inside a specific class

Is there a way for me to extract each of those strings using jQuery or JavaScript? For example, 'fight club', 33 Main Street, Houston, etc. <span class="cart_text2"> Fight Club <br> 33 Main Street, <br> Hou ...

Unable to implement str.replace function within HTML code

Within my Angular app, I'm looking to replace all instances of _ within a string. In my controller, the following code achieves the desired outcome: alert("this_is_string_".replace(/_/g, " ")); However, when attempting to implement the same code wit ...

Preventing the Spread of JavaScript Promises

Consider a scenario where there is a promise chain structured as shown below. The goal is to prevent func3 or func4 from being called when func2 is invoked. AsyncFunction() .then(func1, func2) .then(func3, func4) Currently, throwing an error in func2 res ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

Utilizing shared functions defined across different controllers

Can I utilize the code within these controllers for other purposes? .controller('GenericController', ['$scope', '$controller', '$rootScope', '$dialogs', '$state', '$http', '$modal& ...

Transmit a PDF byte array from JavaScript to PHP using Ajax, then utilize the PHP file to send an email

I am facing a particular issue. Currently, I am utilizing the pdf-lib library for JavaScript to generate a PDF. The last step involves creating a uint8array: const pdfBytes = await pdfDoc.save() My goal is to transmit these pdfbytes via AJAX to a PHP fi ...

Struggling to connect HTML with CSS in Hugo

I am experimenting with a pre-fabricated theme in Hugo and incorporating some Bootstrap codes. I want to change the color of all links when displayed or hovered over. Despite searching extensively, I have been unable to achieve this through the use of CSS ...

Tips for utilizing the AngularJS filter to group by two columns in Angular

In my array of objects, each item has three properties: 1. name 2. team 3. age http://jsfiddle.net/HpTDj/46/ I have successfully grouped the items by team, but I am unsure how to group them by both team and age in my current code. I want to display the ...

What is the best way to resize an image to fit its surroundings within a nested box?

Have you ever heard of a website called SPAM? It has a unique homepage that I want to replicate using JavaScript, jQuery, and some CSS. My main challenge is figuring out how to adjust the image size to match the center box on the page. I want to create th ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Exploring the Dynamic Routing Features of Next.js

After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me. Currently, my focus is on implementing dynamic routing in my application - Starting with my live/index.js file - (Where I utilize ge ...

Unexpected display issue with Bootstrap-vue navbar component

I am currently working with bootstrap-vue and trying to implement a navbar component within my application. I followed the first example provided in the documentation at this link. All the necessary dependencies are installed as per the bootstrap-vue instr ...

Guide to making a Typescript interface by combining elements from two separate interfaces without utilizing inheritance

Programming Language: Typescript I am looking to combine the properties of two interfaces as the value of an indexable-type within a third interface. Interface 1: export interface Employee { id: string name: string } Interface 2: export interfa ...