Creating a transparent background in a three.js canvas: a step-by-step guide

I came across a wave particle animation on Codepen (https://codepen.io/kevinsturf/pen/ExLdPZ) that I want to use, but it has a white background. However, when I try to set the body background to red, it doesn't show up once the canvas is rendered.

I also attempted to set the alpha value to 0 with the following code:

    renderer.setClearColor( 0xffffff, 0);

How can I achieve transparency in this animation?

Answer №1

To make the background transparent, you must pass alpha as true to the renderer:

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

After that, you can set it to be transparent:

renderer.setClearColor( 0x000000, 0 );

We also included a black background color for the div so you can observe it in action

.waves { 
  height: 100vh;
  background-color: black
}

/* 

ThreeJs custom waves
Original script by ThreeJS : https://threejs.org/examples/canvas_particles_waves.html
Modified version for Cloudoru by Kevin Rajaram : http://kevinrajaram.com
Date: 08/14/2014


*/

var SEPARATION = 40, AMOUNTX = 130, AMOUNTY = 35;

var container;
var camera, scene, renderer;
/*

if (window.WebGLRenderingContext){
    renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
    }
else {
    renderer = new THREE.CanvasRenderer();
    }
*/

var particles, particle, count = 0;

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

init();
animate();

function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );
    if(container) {
        container.className += container.className ? ' waves' : 'waves';
    }

    camera = new THREE.PerspectiveCamera( 120, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.y = 150; //changes how far back you can see i.e the particles towards horizon
    camera.position.z = 300; //This is how close or far the particles are seen
    
    camera.rotation.x = 0.35;
    
    scene = new THREE.Scene();

    particles = new Array();

    var PI2 = Math.PI * 2;
    var material = new THREE.SpriteCanvasMaterial( {

        color: 0xFFFFFF, //changes color of particles
        program: function ( context ) {

            context.beginPath();
            context.arc( 0, 0, 0.1, 0, PI2, true );
            context.fill();

        }

    } );

    var i = 0;

    for ( var ix = 0; ix < AMOUNTX; ix ++ ) {

        for ( var iy = 0; iy < AMOUNTY; iy ++ ) {

            particle = particles[ i ++ ] = new THREE.Sprite( material );
            particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 );
            particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) - 10 );
            scene.add( particle );

        }

    }

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

    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 animate() {

    requestAnimationFrame( animate );

    render();

}

function render() {

    var i = 0;

    for ( var ix = 0; ix < AMOUNTX; ix ++ ) {

        for ( var iy = 0; iy < AMOUNTY; iy ++ ) {

            particle = particles[ i++ ];
            particle.position.y = ( Math.sin( ( ix + count ) * 0.5 ) * 20 ) + ( Math.sin( ( iy + count ) * 0.5 ) * 20 );
            particle.scale.x = particle.scale.y = ( Math.sin( ( ix + count ) * 0.3 ) + 2 ) * 4 + ( Math.sin( ( iy + count ) * 0.5 ) + 1 ) * 4;

        }

    }

    renderer.render( scene, camera );

    // This increases or decreases speed
    count += 0.2;

}
canvas{
  position: absolute;
  top:0;
  left:0;
  z-index:2;
}

.waves { 
  height: 100vh;
  background-color: black
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r68/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

Using JavaScript to sort data within specific timeframes

How can I extract data based on timestamps greater than 06? "use strict" const data = [ {timestamp: "2020-04-23 05:05", totalAvg: 2.596211180124224}, {timestamp: "2020-04-23 05:10", totalAvg: 3.22052273203436}, {timestamp: "2020-04-23 05:15", t ...

basic fading javascript image rotator

While looking for a simple fade image rotator, I stumbled upon this old post: Simple fade javascript image rotator request I finally found what I was searching for: $(function() { $('#fader img:not(:first)').hide(); $('#fader img').c ...

Steps for positioning an element to the left and center of a div

I'm having trouble aligning my two elements in a simple horizontal menu to the middle left. I want them to have a margin of 5px on the left and right sides. Here is a screenshot and CSS style: https://i.stack.imgur.com/vzO5D.png .body_clr { wid ...

Experiencing difficulties with setting the width of owl carousel

Here is the HTML code snippet: <div class="row"> <div class="col-lg-7 col-sm-6"> <div class="owl-carousel" id="homeCarousel"> <div class="item"> <img src="images/brela.jpg" alt="brela makarska"> </d ...

Add a style to every div except for the final one

I've attempted to add a unique style to all divs with the same class within a parent div, except for the last one. Strangely, my code doesn't seem to work as expected for this particular case. Can anyone spot what I might be overlooking? Right no ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

Display pie charts on a Google Map

Utilizing a combination of JavaScript and GoogleMaps technology Within my application, there exists a screen showcasing a Google Map. In addition to this map, I have incorporated statistics detailing Population growth data displayed in the form of Pie Cha ...

The Redis port and host remain unset despite having defined environment variables

While utilizing the redis npm package, I encountered an issue where the host and port values were showing as undefined when trying to connect. Even after checking my process.env object, I could see that the values were properly set. Strangely, it only beca ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

Maintain the markup created by jQuery inside the AJAX function called by setInterval

In the code snippet below, real-time markup is generated and automatically updates using the setInterval function. The markup includes buttons and hidden content within div elements. Each button reveals its corresponding div, but the div reverts to a hid ...

Styling conditionally with Dash Bootstrap using an IF statement

I am looking to implement a feature where text in a column is displayed in two different colors based on its value, using Dash bootstrap and various HTML components. For example, consider the following table: Value Yes No Yes Yes No The goal is to displa ...

What are the steps to ensure HTML5 video fills the entire height and width of the browser window?

Is there a way to make a video fill the entire width and height of the browser on first page load using bootstrap? I am currently facing some issues with achieving this. The code that I have been using seems to work, but the height ends up being more than ...

The inline $Emit function is not generating the correct random number when using Math.random()

I've been diving into the concept of $emit event in Vue and came across this tutorial: . I tried implementing something similar using Vue2.js, but every time I click the button, it gives me a rounded number instead of a random number like in the guide ...

How to add Bootstrap and Font Awesome to your Angular project

After attempting to add Bootstrap and Font Awesome to my Angular application, I am encountering issues. I utilized the command npm install --save bootstrap font-awesome and included both libraries in the angular.json file as follows: "styles": ...

Eclipse - enhancing outline view by utilizing require.js define(...)

My code is structured within the define(...) function in the following format: define(['angular'], function(angular) { function foo () { console.log("Hi") ; } function foo2 () { console.log("Hi") ...

menu with dropdown options within dropdown options

I am experiencing an issue with creating a nested menu within my navigation header. Specifically, under the "Reports" section, I want to have two submenu items named "Global Shop" and "Ndustrios". When hovering over either of these submenus, additional men ...