Transparent Background Feature in the SoftwareRenderer of Three.js

Experimenting with one of the three.js demos found at

Is there a way to create a transparent background? The code snippet provided doesn't seem to work for the SoftwareRenderer, although it works for the WebGLRenderer. However, I specifically need to use the SoftwareRenderer.

renderer = new THREE.SoftwareRenderer( { alpha: true } );
renderer.setClearColor( 0x000000, 0 );

Any suggestions on how to achieve this?

The entire script is stated below:

        var container, stats;
        var camera, scene, renderer;
        var group;
        var mouseX = 0, mouseY = 0;

        var windowHalfX = window.innerWidth / 2;
        var windowHalfY = window.innerHeight / 2;

        init();
        animate();

        function init() {

            container = document.getElementById( 'container' );

            camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
            camera.position.z = 500;

            scene = new THREE.Scene();

            group = new THREE.Group();
            scene.add( group );

            // Loading earth texture

            var loader = new THREE.TextureLoader();
            loader.load( 'textures/land_ocean_ice_cloud_2048.jpg', function ( texture ) {

                var geometry = new THREE.SphereGeometry( 200, 20, 20 );

                var material = new THREE.MeshLambertMaterial( { map: texture, overdraw: 0.5 } );
                var mesh = new THREE.Mesh( geometry, material );
                group.add( mesh );

            } );

            // Creating shadow element

            var canvas = document.createElement( 'canvas' );
            canvas.width = 128;
            canvas.height = 128;

            var texture = new THREE.Texture( canvas );
            texture.needsUpdate = true;

            var geometry = new THREE.PlaneBufferGeometry( 0, 0, 0, 0 );
            var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );

            var mesh = new THREE.Mesh( geometry, material );
            mesh.position.y = - 250;
            mesh.rotation.x = - Math.PI / 2;
            group.add( mesh );

            renderer = new THREE.SoftwareRenderer( { alpha: true } );
            renderer.setClearColor( 0x000000, 0 );
            renderer.setSize( window.innerWidth, window.innerHeight );

            container.appendChild( renderer.domElement );

            document.addEventListener( 'mousemove', onDocumentMouseMove, false );

            //

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            windowHalfX = window.innerWidth / 2;
            windowHalfY = window.innerHeight / 2;

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        function onDocumentMouseMove( event ) {

            mouseX = ( event.clientX - windowHalfX );
            mouseY = ( event.clientY - windowHalfY );

        } 

        //

        function animate() {

            requestAnimationFrame( animate );

            render();
            // stats.update(); 

        }

        function render() {

            camera.position.x += ( mouseX - camera.position.x ) * 0.05;
            camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
            camera.lookAt( scene.position );

            group.rotation.y -= 0.005;

            renderer.render( scene, camera );

        }

**edit: Here's the softwareRenderer.js file link used. Accessible through Sublime Text.

Answer №1

To get it working, make sure to:

renderer = new THREE.SoftwareRenderer({ alpha: true}); // ensure this is set correctly, although I have not tested with false....

I have successfully made it work for you, you must modify renderers/SoftwareRenderer.js by replacing the following line:

  /*line85 :*/  context.fillRect( 0, 0, 0, 0 ); 

this stops the background from being rendered

 /*line596 :*/  data[ poffset ++ ] = 0; 

This will halt a redraw and fill in the blocks again...

I tested it using a scene and a plane, as well as a CSS HTML image background.. I adapted this , removing the earth to simplify it for quick testing

Note that this is a dynamic scene

Answer №2

When initializing the constructor, include this line of code:

var alpha = parameters.alpha;

Instead of setting

context.fillStyle = clearColor.getStyle();

replace it with

context.fillStyle = alpha ? "rgba(0, 0, 0, 0)" : clearColor.getStyle();

Make sure to replace all occurrences of

data[ i + 3 ] = 255;

with

data[ i + 3 ] = alpha ? 0 : 255;

and update

data[ poffset ++ ] = 255;

to

data[ poffset ++ ] = alpha ? 0 : 255;

Check out the Demo - the third one from the top utilizes SoftwareRenderer

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

Is there a way to generate a fresh array by filtering an array of objects based on a single value?

I am currently working with an array of objects: const dummyLinkRows = [ { id: 'entity:link/1:en', categories: [ { name: 'Human Resources' }, { name: 'Social' } ], nam ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Utilize a dual-color gradient effect on separate words within the <li> element

I am attempting to display the fizz buzz function in an unordered list, with each word being a different color ('fizz'-- green, 'buzz'--blue) as shown here: https://i.sstatic.net/Yvdal.jpg I have successfully displayed "fizz" and "buz ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

Tips for accessing the HTML code of a TextBox in JavaScript while utilizing HTMLEditorExtender

Currently, I am utilizing the HTMLEditorExtender ajax tool on my website. The data is being saved in HTML format into the database and then retrieved within my project without any issues. However, there is a setback that I have encountered... When attemp ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

How can the middle mouse button be used to move or pan the camera in Three.js?

Is there a way to enhance the functionality of Three.js with OrbitControls.js to include a feature that allows users to move the camera by pressing and holding the middle mouse button, similar to what is found in 3D programs? Alternatively, could this be ...

Manipulating dynamic elements using jQuery

I am facing an issue with manipulating a dynamically created element using jquery fonticonpicker. Even though I have tried to modify the icon using the code below, it has not been successful as .icons-selector i is generated by the plugin itself. In the p ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

Sending data to server using Ajax and jQuery

Hey there, experiencing a little hiccup in the back-end of my system when I try to submit my form. It keeps showing me an error saying Unidentified index: file1 . Can't seem to pinpoint where the issue lies in my code. Even though I'm no beginner ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

What is the best method for incorporating a JavaScript redirect into an Android WebView?

My issue involves loading a page into a webview. Typically, when I use the code webview.loadUrl(url); it functions as expected. The url contains a javascript code that redirects the page. Here is the javascript code: <script type="text/javascript"> ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

What could be the reason for the absence of display in THREE.BoundingBoxHelper?

https://i.sstatic.net/2Qf7b.png I was able to successfully display a box before, but now I am facing an issue. I decided to strip down everything to experiment with expanding boxes using collada models, but unfortunately the box is not showing up. functio ...

What is the best way to preserve the state of child components after being filtered by the parent component?

I've been working on a small application using create react app to enhance my skills in React, but I've hit a roadblock with managing the state. The application maps through JSON data in the parent component and displays 6 "image cards" as child ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...