Animating color on a JSON model when loaded in three.js

Can you animate the colors of a loaded JSON model in three.js?

In my code, I used the ObjectLoader() to render the model. Now, I want to be able to animate the color of the model after it's been loaded.

        var objectLoader = new THREE.ObjectLoader();
        var model;
        objectLoader.load("path/to/model.json", function ( obj ) {

            object.traverse( function ( child ) {
                if ( child instanceof THREE.Mesh ){

                    model = child.material.color;
                }
            });
            scene.add( obj );
        } );

I'm interested in using GSAP for the animation. I know I can change the color of the model with

model.material.color.setRGB(1,1,1);
, but is there a way to animate it as well?

Answer №1

My experience with GSAP is limited, as I tend to favor Tween.js which comes bundled with Three.js and is a more lightweight library ;)

However, the concept of changing colors remains the same, in my opinion.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var colorStart = new THREE.Color("red");
var colorEnd = new THREE.Color("blue");

var box = new THREE.Mesh(new THREE.PlaneGeometry(5, 5, 10, 10), new THREE.MeshBasicMaterial({
  wireframe: true
}));
box.material.color.copy(colorStart);
scene.add(box);

var tween = new TWEEN.Tween(box.material.color).to(colorEnd, 2000).easing(TWEEN.Easing.Bounce.Out);
tween.start();


render();

function render() {
  requestAnimationFrame(render);
  TWEEN.update();
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/90/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org/examples/js/libs/tween.min.js"></script>

Visualized easings

Answer №2

There is another method for achieving this through the three.js animation system. It is uncertain if GSAP supports this functionality, or if GSAP is primarily focused on animating HTML attributes? If so, combining GSAP with an HTML-based graphics framework like A-Frame may yield better results.

Referencing one of the official examples —

var colorTrack = new THREE.ColorKeyframeTrack(
  '.material.color',
  [ 0, 1, 2 ], // keyframe times
  [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ], // colors: r1, g1, b1, r2, g2, b2...
  THREE.InterpolateLinear
);
var clip = new THREE.AnimationClip( 'myclip', undefined, [ colorTrack ] );
mixer = new THREE.AnimationMixer( mesh );
var clipAction = mixer.clipAction( clip );
clipAction.play();

// in render loop
mixer.update( clock.getDelta() );

Alternatively, using another animation library like tweenjs is a common practice as it can be more user-friendly based on your requirements.

Based on three.js r90

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

Issue with jQuery Cycle causing images not to load in IE all at once, leading to blinking

When using the jQuery Cycle plugin in IE8 (as well as other versions of Internet Explorer), I am encountering an issue. My slideshow consists of 3 slides, each containing a Title, Description, and Image. The problem arises when viewing the slideshow in I ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

What could be causing the abundance of API calls from Yandex Metrica?

In my Nextjs SPA, there is an iframe widget that is rendered using React. Inside this widget's index.html file, I have inserted the Yandex Metrica script and set up a goal tag to track user clicks on the registration button. The goal tracking is wor ...

Vertical alignment in material-ui's Grid component is not functioning as expected

I have been working on this code snippet to center a button both vertically and horizontally. However, it seems like the button is not positioned correctly along the vertical axis. Any advice or guidance would be greatly appreciated! Could someone assist ...

Dynamically load select options using Ajax

I'm a newcomer to javascript and ajax, and I'm working on implementing Ajax to display the current category on my HTML select in a CodeIgniter project. Below is the code snippet: HTML: <select class="form-control" name="category" id="categor ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

Tips on deleting specific elements from an array by utilizing the splice method

Here are the details of my first array: [ { members: [ '60ee9148104cc81bec3b97ab' ] } ] And this is the second array: [{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "< ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Switching between pages and updating the URL without needing to refresh the page, while still maintaining the content even after a refresh

After experimenting with jQuery's load() method to dynamically change content without refreshing the page, I encountered a recurring issue: the URL remains unchanged. Even when attempting to use history.pushState() to modify the URL, the problem pers ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

The React page loads before verifying the clients' permissions

In my application, I am using a Javascript query to fetch the data of the current user. This data is then used to verify the user's access permissions for different pages in my React app with the help of Apollo Client and GraphQL. Unfortunately, ther ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

Tips for creating brief animations

I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key. The animation is controlled by a switch statemen ...

What is the sequence in which middleware and callback functions are executed in Node.js?

I'm just starting out with node.js, and I have a file called app.js that references another file named xmlParser.js. The purpose of this is to parse an input xml file using the xml2js node module. Here's a snippet from app.js: //Require modules ...

the onreadystatechange function is not being triggered

When trying to call the show_Message function, I expected an alert box to appear. However, the onreadystatechange is not working as expected. All other alert boxes are functioning properly. Below is my JavaScript function: function send_Message(){ var ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...