Guide to creating fog animations in three.js

I'm attempting to adjust the fog density using tweening, but for some reason, it doesn't seem to be working. Here are my default settings:

var camera, densityFog, colorFog2;
                    colorFog2 = 0xfee2ed;
                    densityFog = 0.25;
                    scene.fog = new THREE.FogExp2(colorFog2, densityFog);

Here is my attempt using GSAP and tweenjs:

tween = new TWEEN.Tween(scene.fog)
                .to({densityFog: 0.02}, 1000 )
                .easing(TWEEN.Easing.Exponential.InOut)
                .onComplete(function() { }).start();
                    
                gsap.to(scene.fog, {
                        duration: 2,
                        densityFog: 0.02,
                        onUpdate: function () {
                            controls.update();
                            isZoomed = 0;
                            controls.enabled = false;
                            
                        },
                    });

Could someone provide some guidance on how to achieve this?

Answer №1

This solution utilizes the gsap library

Create an object like myfog = { value: .5 } and animate its value property to achieve your desired effect.

Then, within the onUpdate function, update the scene.fog to a new THREE.FogExp2 instance with the current value of myfog.value.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
camera.position.y = 2;

// Initialize the object and fog here
var myfog = { value: .5 }
scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);

var geometry = new THREE.BoxGeometry(1, 1, 5);
var material = new THREE.MeshBasicMaterial({
  color: 0xff0000
});
var mesh = new THREE.Mesh(geometry, material);

scene.add(mesh);

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

function render() {
  renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

animate();

// This part animates the fog
gsap.to(myfog, {
  duration: 2,
  value: 0.002, // The end value
  onUpdate: function() {
    // Update fog with current myfog value
    scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);
  },
  // Set animation to yoyo and repeat infinitely
  yoyo: true,
  repeat: -1,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.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

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...

Implementing a click event on a selection option – tips and tricks

When I want to select an option, I can use the following script: Javascript $("#practice-area optgroup option").click(function(){ // insert your function here }); HTML <select name="practice-area" id="practice-area"> <option value="0">S ...

What is the best way to retrieve the element at the current cursor position inside an iframe

I'm currently working on a script that is intended to retrieve the element positioned at the cursor's location within an iframe. The code I am attempting to implement should be able to identify the deepest child element at the cursor's posit ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

I'm having trouble with my AngularJS Spinner directive

Check out this simple directive I created to display a spinner on my button while something is happening remotely: http://plnkr.co/edit/rAJ4X7A3iidmqUD2M63A?p=preview Here's the html: <!DOCTYPE html> <html ng-app="app"> <head> ...

Creating a new line in the content of a MatDialog in Angular 7

I have a situation where I am using MatDialog and attempting to insert a new line in the content definition. I've tried using both \n and </b>, but neither of them seem to work. Is there an alternative way to achieve this without manually e ...

Raycasting in Three.js without using a camera

Most examples I come across show how to use the raycaster with the camera, but I am looking for a way to cast a ray from Point A to Point B. Although my raycaster successfully retrieves Helpers, Lines, etc., it doesn't seem to recognize my sphere. I ...

Rearrange list items by dragging and dropping

Here is the HTML and TypeScript code I have implemented for dragging and dropping list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop List in Green Area: </h4> <ul class="unstyle"> <l ...

Steps for iterating through an array within an object

I currently have a JavaScript object with an array included: { id: 1, title: "Looping through arrays", tags: ["array", "forEach", "map"] } When trying to loop through the object, I am using the following ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...

Creating a Client-side Web Application with Node.js

As I search for a versatile solution to bundle an HTML5 web application (without server dependencies) into a single executable app using node.js and the Linux terminal on Ubuntu, I have experimented with tools like wkpdftohtml and phantomjs. However, these ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...