How can I create a continuous color transition effect for the scene background in Three.JS using lerp?

I am currently working on smoothly transitioning between multiple colors for a Day/Night Cycle in the background of my scene. Is it possible to achieve this effect? If so, how can it be done? Additionally, I am curious if it is feasible to incorporate GUI elements into Three.JS, specifically within the Three.JS Editor. Any insights on this would be greatly appreciated! Below is the test code I have been experimenting with, but unfortunately, none of my attempts have been successful.

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

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

/*
//cycleloop();
function cycleloop(){
    var day = new THREE.Color(0xB8F4FF);
    var duskdawn = new THREE.Color(0xFF571F);
    var night = new THREE.Color(0x17012D);
    var clock = new THREE.Clock();
    clock.start();
    var speed = 10;
    var delta = 0;
    delta = clock.getDelta();
    var col = new THREE.MathUtils.lerp(day, duskdawn, 0.1);
    //scene.background.setColor(new THREE.MathUtils.lerp(day, duskdawn, delta));
    scene.background = new THREE.Color(new THREE.MathUtils.lerp(day, duskdawn, delta));
    requestAnimationFrame(cycleloop);
    //renderer.render(scene, camera);
}

cycleloop();
*/
function cycletime() {
  var time;
  //scene.background.setColor(new THREE.MathUtils.lerp(day, duskdawn, time));
  scene.background = new THREE.Color(new THREE.MathUtils.lerp(day, duskdawn, time));
}
for (i = 0; i < 100; i++) {
  cycletime();
}

/*
let then = 0;
function animate(now) {
  now *= 0.001;  // make it seconds

  const delta = now - then;
  then = now;

  object.position.z += delta * speedInUnitsPerSecond;

  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
*/

//vartween = new TWEEN.Tween(day).to(duskdawn, 5000).start();

//scene.background.setColor(new THREE.MathUtils.lerp(day, duskdawn, 0.1));
//scene.background.setColor(tween);

If further clarification or details are needed, please do not hesitate to reach out! Thank you!

Answer №1

Your method of linear interpolation is incorrect. Please try implementing it using the following code snippet:

let camera, scene, renderer;

let t = 0;

const day = new THREE.Color(0xB8F4FF);
const duskdawn = new THREE.Color(0xFF571F);

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();

  const geometry = new THREE.BoxBufferGeometry(0.2, 0.2, 0.2);
  const material = new THREE.MeshNormalMaterial();

  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

  t += 0.01;
  
  // Linear Interpolation calculation
  scene.background.copy(day).lerp(duskdawn, 0.5 * (Math.sin(t) + 1));

  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55213d27303015655b646766">[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

Displaying radio values in an Angular ng-repeat directive

I am new to Angular and facing difficulties in capturing the selected radio value when using ng-repeat. The documentation is a bit unclear on this matter. Any assistance or guidance would be highly appreciated. <div ng-repeat="item in ed"> <lab ...

Update destination upon click

I'm new to JavaScript and attempting to modify a redirect link using checkboxes that will modify the URL, followed by a button that will use the updated URL. However, I'm facing some challenges with my code and could use some guidance. Here is t ...

Using SWR, retrieve data in client components consistently for each request in a Next.js version 13.3 environment

I recently upgraded to Next.js 13.3 with the app dir set up. I have a simple component that displays the current date. However, it only updates the date once and then doesn't update again until I rebuild the app. In Next.js 12, the date would update w ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Retrieve an array containing various values of a single element with the help of Protractor

Currently, I am in the process of testing an application that showcases graphs using rickshaw and d3. The tests are being run with protractor and jasmine. It's worth noting that this question is not specific to this particular scenario but rather more ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line: json-server --port 4000 --delay 1000 db.json However, when attempting to achieve the same delayed response using json-server as a module, the following code ...

Retrieve every checklist associated with all the cards in Trello

Can I retrieve all checklists from every card that I am a member of in a single API request? I am hoping to use this path: Trello.get('members/me/cards/all/checklists', function(checklist) { ... }); Is it feasible to achieve this with just one ...

Using classic ASP to populate a JavaScript array from a VBScript drop-down menu

To create a JavaScript array based on the selected values from multiple drop down lists, each with the same name due to being generated in a for loop, the following code snippet is currently being used: <script language="JavaScript"> var array ...

Confirming the validity of JSON data in multiple dimensions

Does this text require any modifications or improvements? I'm dealing with a set of data that closely resembles the actual information and I want to make sure that my JSON file is correctly structured with nested objects and arrays. let data = ...

Adding a model to a canvas in Three.js: A step-by-step guide

Can somebody please assist me? I'm attempting to incorporate my model into a canvas that I've inserted into the HTML document. However, the code below does not seem to be functioning properly: function main() { const container = ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. T ...

Implementing Javascript to allow users to interact with a dynamic table

All user entries are captured and stored in an array. The array output should be displayed in a dynamic table which includes edit and delete options. If the number of entries exceeds 3, then the table should also have previous and next navigation options. ...

Having trouble loading texture locally in THREE.js?

Here's the scenario: I have a local file where I attempt to load a texture using the following code: var texture = THREE.ImageUtils.loadTexture( 'image.jpg' ); var cubeGeo = new THREE.CubeGeometry( 50, 50, 50 ); var cubeMat = new THREE.Mesh ...

Vue and Summernote issue: Model content doesn't display in form when loaded from database

I am having an issue with my form that uses the Summernote wysiwyg editor multiple times. When I fill out the form, everything works correctly - the model is updated, content is displayed, and the data is saved to the database. However, when I try to edit ...

Show the button when the mouse moves over the image

Here is the snippet of code I am working with: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <script src="Js/jquery.min.js"></script> <script type="text/javascript"> $(document).r ...

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and doc ...