Modify the Color of Mesh by Clicking a Button in THREE.js

Having trouble changing the color of a sphere mesh in three.js when a button is pressed. When using mesh.material.color.SetHex() with a Click event listener, it doesn't work. However, it works fine when used outside the event listener. Here's my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="three.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="propertiesPanel">
        <p>Properties Panel</p>
        <p>Albedo Colour</p>
        <input type="text" id="albedo">
        <button id="btn">Change</button>
    </div>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerWidth, 0.1, 1000);
        camera.position.z = 5;
        var renderer = new THREE.WebGLRenderer({antialias: true});

        renderer.setClearColor("#4b4b4b");
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
        window.addEventListener("resize", () => {
            renderer.setSize(window.innerWidth, window.innerHeight);
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
        })


        var geometry = new THREE.SphereGeometry(1, 20, 20);
        var material = new THREE.MeshLambertMaterial({color: 0xFFCC00});
        var mesh = new THREE.Mesh(geometry, material);

        scene.add(mesh);
        var btn = document.getElementById("btn");
        btn.addEventListener("click", () => {
            mesh.material.color.setHex( 0xc24a4a );
        });

        var light = new THREE.PointLight(0xFFFFFF, 1, 500);
        light.position.set(10, 0, 25);
        scene.add(light);

        renderer.render(scene, camera);
    </script>
</body>
</html>

Answer №1

Instead of constantly re-rendering, your sphere's color may change without the updated image being shown. To fix this issue, include the following code snippet at the conclusion of your script:

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

Everything else in your script should operate as intended.

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

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

Leverage variables in the path of your Express.js route

Currently in the process of developing a web application using the MEAN stack and I have a specific scenario in mind: Users should be able to sign up, but then they must also register at least one company. Upon registering a company, the base URL struct ...

Template string use in Styled Components causing issues with hover functionality

I have a styled component where I am trying to change the background color when its parent is hovered over. Currently, the hover effect is not working and I'm unsure why. const Wrapper = styled('div')` position: relative; margin-bott ...

Troubleshooting Azure SDK: Tips for Displaying the Appropriate REST API

Currently, I am utilizing the Azure JS SDK to interact with Postgres in Azure using various modules such as @azure/arm-postgresql, @azure/identity, and @azure/functions. My main goal is to access the underlying REST Api for debugging purposes. For instanc ...

Tips for adding multiple audio tracks to a video using JavaScript

I am currently working on a video player that can play MP4 videos without audio files embedded in them. In addition to the video, I have two separate audio files available in English and Italian languages. To implement language selection functionality, ...

Tips on saving a form submit button data to localStorage

As a newcomer, I am on a quest to make this function properly. My goal is to create a form where the submit button saves data to the localStorage. Here's what I have tried thus far. <script> function storeRecipe() { localStorage.setItem($(" ...

Tips for updating button appearance when clicked using React Bootstrap

Is there a way to add custom styling to a toggle button in React? I want the button to change color when selected, but the issue is that the color reverts back to default once the click is released. Can anyone assist me with this? Below is my React Compon ...

Clicking a link will trigger a page refresh and the loading of a new div

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> $(window).load(function () { var divs = $( #add_new, #details"); $("li a").click(function () { ...

Why does the array format of the values saved in app.locals seem to disappear when they are accessed in the view?

I have created a date values array and stored it in an app.locals variable using the code snippet below: prepDataList.forEach(function(item){ var str = item.createdAtDate.toDateString(); //str = str.substring(4, 10); labelsArray.push(str); counts ...

Switching the color scheme between mobile and desktop devices to make the background look

As a newcomer to threejs, I have just begun learning and developing with this technology. I am aware that certain features may be different on mobile browsers compared to desktop ones due to limitations. However, I have encountered an issue that I cannot s ...

Encountered a error 500 while attempting to POST using Postman in Node.js

After successfully setting up the server, I encountered an issue when attempting to create a user using Postman with the details in Application/JSON format. The server responded with: POST /sign-up 500. Initially, I tried specifying utf-8 without succes ...

essential elements for mapping an array using typescript

Struggling to iterate through an array of objects, each with a unique id created by uuidv4(), resulting in a string type. TypeScript is giving errors (( Type 'String' is not assignable to type 'Key | null | undefined')) due to the &apos ...

What is the method for turning off client-side validation for a specific field with jQuery when a checkbox is selected?

This is the HTML code used in my MVC Razor page. <form> <input id="inputLPR" asp-for="LicensePlateNo" class="form-control"/> <input type="checkbox" id="isEnableBypass"><label for=&qu ...

How can the first paragraph value of a div be found using jQuery in Next.js?

How can I retrieve the value of the first <p> tag within my div when a button inside the same div is clicked? Despite attempting to use $(this), it doesn't appear to be functioning as expected. Take a look at the code snippet below: <div cla ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

How can I display a div within a parent container in Angular 2?

Instead of pasting my loading modal pop-up to every page in the app, I want it to appear at the parent component (i.e. "app.component.ts"). This way, I can easily call it multiple times throughout the application. Now, I have pages with different routes t ...

Retrieve information from D3 line interpolation functions

I'm currently working on creating a D3 graph that features a shaded area in the middle. The top part of the shaded region aligns with the line graph. For reference, the data structure I'm using is as follows: line = [ {x: 0, y:1}, {x: 1, y: ...

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...

Is it possible for URLSearchParams to retrieve parameters in a case-insensitive manner

Is it possible for URLSearchParams to search a parameter without being case-sensitive? For instance, if the query is ?someParam=paramValue, and I use URLSearchParams.get("someparam"), will it return paramValue? ...