Selecting a HEX code from a color picker to configure three.js as a string

Recently, I've been using a color picker from jscolor.com that outputs colors in the format of FFA6A6. The challenge I'm facing is integrating this color output with three.js, which requires the color to be in the format of 0xFFA6A6. As much as I try, I can't seem to figure out how to make this conversion without turning it into a string.

For example, I need to change "FFA6A6" to FFA6A6 in order for three.js to recognize it properly. Below is the code snippet showing my attempts:

function updateNoseColor(){
    scene.remove(nose);
    var geometry = new THREE.ConeGeometry( .4, 1, 32 );

    var material = new THREE.MeshBasicMaterial( {color: document.getElementById("nosecolor").value} );
    //I'm struggling with converting the color value to meet three.js requirements
    var nose = new THREE.Mesh( geometry, material );
    scene.add(nose);
}

I appreciate your time and expertise in helping me find a solution to this issue. If there's a simple way to remove quotes and add '0x', please let me know. Thank you!

EDIT: I attempted using ParseInt to convert to decimal, but unfortunately, it was not accepted by three.js.

Answer №1

You have the option to utilize the Color class from three.js, which can be found in this reference. Here is an example:

var color = new THREE.Color("#FFA6A6"); // Note: "FFA6A6" alone won't work!
color.getHex(); // Result will be 0xFFA6A6

Instead of:

var material = new THREE.MeshBasicMaterial( {color: document.getElementById("nosecolor").value} );

Use:

var material = new THREE.MeshBasicMaterial( {color: new Color(document.getElementById("nosecolor").value)} );

If the value of document.getElementById("nosecolor").value is "#FFA6A6", then:

var material = new THREE.MeshBasicMaterial( {color: new Color("#" + document.getElementById("nosecolor").value)} );

If the value of document.getElementById("nosecolor").value is "FFA6A6" (without # at the beginning), then:

var material = new THREE.MeshBasicMaterial( {color: new Color("#" + document.getElementById("nosecolor").value)} );

To illustrate: you can test the snippet below (based on a three.js example).

function createSquare() {
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

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

    var geometry = new THREE.BoxGeometry(1, 1, 1);
    
    /* BEGIN - CORRECT ANSWER */
    var a = "#" + document.getElementById("nosecolor").value;
    var material = new THREE.MeshBasicMaterial({
        color: (new THREE.Color(a))
    });
    /* END - CORRECT ANSWER */
    
    var cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    camera.position.z = 5;

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

createSquare();
<input type="text" id="nosecolor" value="FFA6A6">

<script src="http://threejs.org/build/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

Remove Angular.js entirely from your system

Is it okay to remove all Angular files and directories without causing any issues? I've searched for information on uninstalling Angular but have come up empty-handed. ...

What is the best way to ensure that the radius of the circle adjusts according to the canvas element in

I've successfully drawn a circle on a canvas element, but now I need to make it responsive. How can I achieve this? I want the radius of the circle to change by a certain amount when the browser width or height changes. How do I calculate this changi ...

Having trouble converting binary data to base64 using GridFS-stream

As I attempt to convert some binary data from uploaded images to base64 in order to display an image, the terminal is throwing back this error: TypeError: Cannot read property 'on' of undefined I find it puzzling, as when I post I also utilize ...

Is there a Node template engine similar to EJS that seamlessly integrates with HTML templates?

Is there a template engine for NodeJS similar to EJS that doesn't alter the original HTML template structure with its use of parentheses? In EJS, one might utilize the following code snippet to embed specific data into the HTML template: <script& ...

What is the best way to create interactive canvases that respond to multiple clicks using JavaScript?

Within the canvas, the code snippet below aims to generate a grid of 10x10 colored boxes with alternating reddish and bluish shades on a gray background. The intention is for each canvas to only respond to mouse interactions when the mouse is within its bo ...

Enhance Your Jekyll Site with the Minimal Mistakes Theme Plugin

Hi there! I'm relatively new to website programming and could really use some assistance. I've been attempting to integrate the jekyll-lunr-js-search (https://github.com/slashdotdash/jekyll-lunr-js-search) into the minimal-mistakes theme, but I&a ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

Trouble with controlling the speed of ajax requests while using vue-multiselect and lodash

I am working on a Vue application that includes a vue-multiselect component. My goal is to load the multiselect options via ajax. To achieve this, I am using lodash.throttle to limit the frequency of ajax requests as the user types in the search criteria ...

What sets defineProps<{({})}>() apart from defineProps({ }) syntax?

While examining some code written by another developer, I came across the syntax defineProps<({})>(). After doing some research, I couldn't find any resources that helped me understand this particular syntax. My Way of Defining Props defineProp ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

Sending data from an AJAX POST request to a Grails Controller

Currently, I am in the process of developing a social networking platform using Grails. However, I have encountered a roadblock when it comes to allowing users on their edit profile page to input a YouTube URL into a text field. By clicking a button, a Jav ...

The tooltip feature in jQuery is experiencing some stuttering issues

Sometimes, images can convey messages better than words. I encountered a strange issue with my self-made jQuery tooltip. I prefer not to use any libraries because my needs are simple and I don't want unnecessary bloat. When I move my mouse from righ ...

Sending SQL data to a Node.js module upon receiving a client request

Currently, I am establishing a connection to a SQL database and retrieving data on the view by using res.json. The client initiates a request - my server employs an MSSQL driver and a connection string to establish a connection with the database and fetch ...

Create an Angular 2 webpack production project and ensure that the dist folder does not contain any source code

I am currently developing a web application using Angular 2 with TypeScript and angular-cli. I needed to test the application on the server without uploading the source code, so I used the command "ng build --prod". Despite deleting all .map files from the ...

How can I make the Box div bigger or smaller?

My goal is to expand and collapse the slider div only for the box where the user clicks. I have achieved this functionality, but a problem arises when I click "read more" - all the boxes expand, which is not the desired behavior. I want only the specific b ...

What is the method for setting a function as the initial value of a state variable?

Here is a function I have: async function setAllValues(value) { await stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .forEach((row) => { temp = ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

"Implement a feature to recognize and handle various file extensions within an npm

I need help with my npm script where I am trying to include both ts and tsx file extensions. My current code snippet is as follows: "test": "mocha ..... app/test/**/*.spec.{ts,tsx}" Unfortunately, the above syntax is not working correctly. Can someone pl ...

Utilizing Javascript for a Stopwatch/Countdown in the Format: 00:00:00

I am currently working with this block of code: function startStopwatch() { vm.lastTickTime = new Date(); $interval.cancel(vm.timerPromise); vm.timerPromise = $interval(function() { var tickTime = new Date(); ...

The Chrome developer tools are unable to locate the HttpRequest

While working in Python, I am utilizing the requests library to make a POST request to a specific URL. However, upon clicking the button, it seems that nothing is happening as per Chrome Developer Tools. No XHR requests are being made and no data is being ...