Maintain the integrity of the original color while applying a transparent background PNG to a cylinder in three.js

With the utilization of the code provided and three.js library, I have successfully managed to apply a transparent background PNG onto a cylinder shape.

actualCode(THREE);
function actualCode(THREE) {
    
    let texture;

    //Load image before rendering
    const loader = new THREE.TextureLoader();
    //Example using an image hosted on Imgur:
    texture = loader.load("https://automation.stickermonkey.shop/codeplayground/glassetch/2-wrapdesign/images/defaultimage.png", function(_tex) {
        console.log("texture loaded");
        // /*Debugging:*/ setTimeout(() => document.body.appendChild(texture.image), 100);
        //views 17.5=front | 355=side | 139.6=back
        renderImageSolo(355);
    });

    function renderImageSolo(angle) {
        //Initialize main renderer / scene
        const solo_renderer = new THREE.WebGLRenderer({
            antialias: true,
            preserveDrawingBuffer: true, // <-- avoid plain black image
            alpha: true
        });
        solo_renderer.setSize(500, 500);
        document.body.appendChild(solo_renderer.domElement);
        const solo_scene = new THREE.Scene();
        //Set camera initial values =(30, 400.0 / 400, 1, 1000)
        
        const camera = new THREE.PerspectiveCamera(80, 500.0 / 500, 1, 100);
        camera.position.set(0, 1.3, 10);
        camera.lookAt(solo_scene.position);
        

        //Draw painting alone original values -= (1.5, 1.5, 8.3, 240, 1, true)
        const paintgeom = new THREE.CylinderGeometry(3, 3, 8.3, 1000, 10, true);
        const paintmaterial = new THREE.MeshStandardMaterial({
            color: (0xddd8d9),
            map: texture,
        });
        
        const paint = new THREE.Mesh(paintgeom, paintmaterial);
        
        
        //Add paint to scene
        solo_scene.add(paint);
        //Rotate paint by angle
        paint.rotation.y = angle;
        
        solo_renderer.setClearColor( 0xddd8d9, 0 ); // the default
        solo_renderer.render(solo_scene, camera);
       
        saveImage(solo_renderer.domElement, "defaultimage.png")
    }

    //Save canvas as image by posting it to special url on server
    function saveImage(canvas, filename) {
        const dataUrl = canvas.toDataURL("image/png");
        const fileNameEnc = encodeURIComponent(filename);
        fetch('./photo_upload.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `data=${dataUrl}&filename=${fileNameEnc}`,
        })
        .then(response => {
            return response.json();
        })
        .then(data => { 
            alert(data.message); //Show ajax result
        })
        .catch(err => { //Handle errors
            console.log(err);
            alert(err.message);
        });
    }
};

The original image appears like this...

https://i.sstatic.net/ApQK6.png

While the current output is displayed as follows..

https://i.sstatic.net/ea59t.png

The wrapping around the side works correctly, but the image turns black instead of maintaining its original colors as desired.

Is there a way to retain the original image colors or even customize them to any preferred choice?

Answer №1

Special thanks to Marquizzo for guiding me towards the correct solution.

Simply changing from MeshStandardMaterial to MeshBasicMaterial didn't completely resolve the problem, however, when combined with...

MeshBasicMaterial( { map: texture, transparent: true } );

I was able to achieve the precise outcome I was looking for.

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

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

Reactjs: Prop Type Error - Issue with retrieving the values from props during data submission

Currently, I am developing a social app where users can post screams, like posts, and add comments. The issue I'm encountering is that I am not receiving the props value when posting a new scream initially, but after refreshing the page, everything wo ...

Ways to iterate and combine two associative arrays in jQuery

I have a total of 15 sections, each known as bases, with their own alphabet buttons. My goal is to link the alphabet letters with their corresponding base/section. For instance, if a user clicks on the letter "B" under base 7, I want to show that the user ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Store the values of the buttons in an array

On my webpage, I currently have a variety of HTML buttons, each with a unique value attribute. My goal is to extract these values and store them in an array. Below is the code snippet I am using: var myArray = []; $(".buttonClass").each(function() { ...

The code is not executing properly in the javascript function

Hello there! I've created a basic login form with JavaScript validation, but for some reason, the code below isn't functioning properly. Here is my HTML and JS code: <head> <script type="text/javascript"> function ha ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Maintain the current application state within a modal until the subsequent click using Jquery

Due to the challenges faced with drag and drop functionality on slow mobile devices, I am considering implementing a modal approach for moving elements from one place to another. Here is how it would work: When a user clicks on an item, it is visually ma ...

The instance is referencing a property or method (...) that has not been defined, resulting in an error during rendering

"Unrecognized property or method "show" is being referenced in the rendering stage. To resolve this, ensure that the property is reactive by including it in the data option for functional components or initializing it for class-based components." This blo ...

AngularJS - activating $watch/$observe event handlers

I am looking for a way to trigger all $watch/$observe listeners, even if the watched/observed value has not changed. This would allow me to implement a "testing only" feature that refreshes the current page/view without requiring user interaction. I have a ...

Saving received JSON data from fetch() API request into a variable

Just starting out with JS and currently working on a project involving retrieving data from an API using a JS Notebook. I'm trying to create a function that can make API calls based on a given URL, and then execute that function twice. The objective ...

The MeshBasicMaterial is producing the wrong color when given input

I've encountered an issue where the shade of the material in my scene is different from what I intended, even though there are no other lights or factors influencing it. Initially, I used meshBasicMaterial thinking that lights were causing the proble ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

The hamburger menu for the responsive navigation bar is not being shown on the screen

I am having trouble creating the "Hamburger menu" on my website. It looks fine, but when I click on it, nothing happens. I have set up an event listener to detect any clicks on the button and toggle the class to display or hide the ul elements accordingly ...

Node.js server experiences a crash after attempting to send a large string using res.send()

I've recently started learning JavaScript and NodeJs. I'm facing an issue with my Nodejs application crashing when a get request is made, specifically when trying to return a large string. app.mjs app.get('/log', function (req, res) { ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

When the `rendered` event is activated in VueJS along with "vue-markdown", the DOM may not be fully prepared yet

Here is the code snippet I am working with: <vue-markdown :source="content" v-on:rendered="afterRenderContent"></vue-markdown> Even after the afterRenderContent method is called, the HTML elements are not yet available. I am looking for a wa ...

Is it possible to update the window title using javascript after a 3-second delay?

How can I alter the title bar of a window with a 3-second delay? This should be achieved using Javascript. www.nazeer.com ...

"Exploring the world of custom middleware in NextJs on a localhost

Question regarding nextjs page middleware: the documentation states that the request object should include geo, IP, ua, cookies, and nexturl properties. Visit the link for more information. I am attempting to retrieve the user's location using page m ...

Executing individual if/each statements to choose specific divs and modify the position of their background images separately

I am currently faced with the challenge of relocating a background image within a div based on the content of a span. The complication arises from the fact that multiple divs share the same class and cannot be individually modified. For instance, each ce ...