Creating a see-through backdrop using three.js

I am facing an issue with setting a transparent background to the canvas using three.js. My code is:

Background.renderer.setClearColor(0xffffff, 0);

However, the background turns black instead of being transparent. How can I make it transparent?


Here is my code snippet:

   var camera, scene, renderer;
   var mouseX = 0, mouseY = 0;
   var p;

   var windowHalfX = site.Width / 2;
   var windowHalfY = site.Height / 2;

   Background.camera = new THREE.PerspectiveCamera( 35, site.Width / site.Height, 1, 2000 );
   Background.camera.position.z = 300;

   // scene
   Background.scene = new THREE.Scene();

   // texture
   var manager = new THREE.LoadingManager();
   manager.onProgress = function ( item, loaded, total ) {
      console.log('webgl, twice??');
   };

   // particles
   var p_geom = new THREE.Geometry();
   var p_material = new THREE.ParticleBasicMaterial({
      color: 0xFFFFFF,
      size: 1
   });

   // model
   var loader = new THREE.OBJLoader( manager );
   loader.load( site.base_url + '/assets/models/head.obj', function ( object ) {

      object.traverse( function ( child ) {

         if ( child instanceof THREE.Mesh ) {

            var scale = 6;

            $(child.geometry.vertices).each(function() {
               p_geom.vertices.push(new THREE.Vector3(this.x * scale, this.y * scale, this.z * scale));
            })
         }
      });

      Background.scene.add(p)
   });

   p = new THREE.ParticleSystem(
      p_geom,
      p_material
   );

   Background.renderer = new THREE.WebGLRenderer();
   Background.renderer.setSize( site.Width, site.Height );
   Background.renderer.setClearColor(0xffffff, 0);

   $('.particlehead').append(Background.renderer.domElement);
   $('#content').on('mousemove', onDocumentMouseMove);
   site.window.on('resize', onWindowResize);

   function onWindowResize() {
      windowHalfX = site.Width / 2;
      windowHalfY = site.Height / 2;

      Background.camera.aspect = site.Width / site.Height;
      Background.camera.updateProjectionMatrix();

      Background.renderer.setSize( site.Width, site.Height );
   }

   function onDocumentMouseMove( event ) {
      mouseX = ( event.clientX - windowHalfX ) / 2;
      mouseY = ( event.clientY - windowHalfY ) / 2;
   }

   Background.animate = function() { 

      Background.ticker = TweenMax.ticker;
      Background.ticker.addEventListener("tick", Background.animate);

      render();
   }

   function render() {
      Background.camera.position.x += ( (mouseX * .5) - Background.camera.position.x ) * .05;
      Background.camera.position.y += ( -(mouseY * .5) - Background.camera.position.y ) * .05;

      Background.camera.lookAt( Background.scene.position );

      Background.renderer.render( Background.scene, Background.camera );
   }

   render();

Answer №1

To achieve a see-through background in three.js, simply include the alpha parameter when initializing the WebGLRenderer.

var renderer = new THREE.WebGLRenderer( { alpha: true } );

The clear color can remain at its default setting.

renderer.setClearColor( 0x000000, 0 ); // this is the default

This code snippet is compatible with three.js version r.71.

Answer №2

When working with versions of Three.js older than v125
In order to properly configure the scene, ensure you set scene.background = null;

Answer №3

To create a see-through background, use the code snippet below.

background.style.opacity = "0.5";

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

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

Error with conversion_obj_three.py due to incorrect syntax

Every time I attempt to convert my obj file, I encounter a syntax error on line 781. C:\Users\Paul>cd "C:\Users\Paul\Documents\GitHub\three.js\utils\converters\obj" C:\Users\Paul\Docum ...

What is the method for assigning a value to a Material UI text field?

Trying to create an autocomplete search feature using EsriGeocode and Material UI. The form includes Street name, City, State, and Zip code fields. Currently facing an issue where the Street name text field displays the entire address instead of just the s ...

Optimal guidelines for logging in

After successfully creating a website using HTML, CSS, and JavaScript, I am now looking to implement a login feature to provide privacy for certain users. I have noticed that some developers use PHP, while others use JS or Node.js for this purpose. However ...

Error: Attempting to access the 'style' property of a non-existent element

function showNotes() { var ThemeValues = "<%=str3%>" if (ThemeValues.value == "MyCity-Social") { document.getElementById("TextBox1").style.visibility = "visible"; document.getElementById("TextBox2").style.visibility = "v ...

What steps can be taken to address issues with the csv to json conversion module?

I'm struggling to correctly match the title and genre in my module. There's a issue in the csv_json module where it doesn't handle properties properly, especially when the title includes "The". //csv file movieId,title,genre 1,"American P ...

The error occurred in async JavaScript parallel code because the task is not recognized as a function

I am attempting to upload an image and update the image URL in the database collection using the code provided below. Controller.prototype.handle = function (req, res, next) { var id = req.params.id, controller = req.params.controller, optio ...

Making a request to an API using the useEffect hook resulted in an error when attempting to iterate through the list of users. The error message displayed was: TypeError: Cannot read property

import logo from './logo.svg'; import './App.css'; import { useEffect, useState } from 'react'; import User from './components/User/User'; function App() { const [user, setUser] = useState([]); useEffect(() => ...

What is the best way to access the onclick calling object?

Is there a way to have a handler on the calling object of the onclick event? <a href="123.com" onclick="click123(event);">link</a> <script> function click123(event) { //I need access to <a> in order to man ...

Finding the ID of the element that was clicked with strict typing

Consider a scenario where we aim to record the ID attribute of a clicked element using the TypeScript code snippet below: onClick(event) { console.log(event.target.attributes.id.nodeValue); } The function above takes the clicked object as an argument, h ...

Using Javascript or Typescript constants along with WebPack being invoked twice

I am encountering an issue with my constants file: collections.ts import {Mongo} from 'meteor/mongo'; import {Chat, Message} from 'api/models'; export const Chats = new Mongo.Collection<Chat>('chats'); export const Me ...

Why is the Node Express API not returning a response?

Recently, I successfully created a node-express API for my project. router.get('/getData', function(req, res) { let data = { title: 'Message Effectiveness – Bar Chart – 1Q', chartData: [ { title: 'Motivatin ...

Do not include the loading of <embed> items while the page is loading

I am currently working on a website project for a friend that involves incorporating a lot of large images. To ensure a smooth loading process, I have implemented a loading overlay while the background content loads. However, I have also added background m ...

What are some alternatives to using multiple slot transclution in an Angular 1.5 component?

In the process of constructing a panel component using angular 1.5, I am looking to embed some markup into this template (which has been simplified): <div class="panel"> <h1>{{ $ctrl.title }}</h1> <div ng-transclu ...

Issue loading a 300 MB file into BigQuery results in a timeout error

Trying to implement the Node.js example shown in the data post request section (located towards the end here: https://cloud.google.com/bigquery/loading-data-post-request) has hit a snag when dealing with larger files. While the sample code functions proper ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

How can I generate 200 divs that are identical but each displaying a unique file (page0.svg, page1.svg..., page200.svg)?

<div class="mySlides"> <img src="1173/page0.svg" style="width:50%"> </div> <div class="mySlides"> <img src="1173/page1.svg" style="width:50%"> </div> My task involves generating approximately 200 similar div codes ...

Different ways to change the value of a variable in an isolated scope using another directive

Utilizing a directive with two modes, edit and preview, multiple times in my codebase. function () { return { restrict: "E", scope : { model : '=' }, [...] controller : function($scope, $el ...

The route seems to be downloading the page instead of properly rendering it for display

I'm facing a simple issue with my Express page - when I navigate to the FAQ route, instead of displaying the page it downloads it. The index page loads fine, and the FAQ page is the only other page available at the moment. I am using EJS templating, a ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...