Creating a transparent background for a Canvas animation with three.js and dat.gui

I'm struggling to set up a background animation on this canvas using three.js. However, the background renders as black instead of transparent. I attempted to adjust it with CSS by adding background-color:transparent;, but to no avail. I've searched for similar issues on Stack Overflow without success. How can I make the canvas transparent? Below are my HTML, CSS, and JS files. Thanks in advance. Here is the link to CodePen. My HTML:

<canvas id="webgl-canvas"></canvas>
<!-- vertexShader -->
<script id="js-vertex-shader" type="x-shader/x-vertex">
attribute vec3 position;
void main() {
  gl_Position = vec4(position, 1.0);
}
</script>

<!-- fragmentShader -->
<script id="js-fragment-shader" type="x-shader/x-fragment">
precision highp float;
uniform vec2 resolution;
uniform float time;
uniform float xScale;
uniform float yScale;
uniform float distortion;

void main() {
  vec2 p = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y);
  
  float d = length(p) * distortion;
  
  float rx = p.x * (1.0 + d);
  float gx = p.x;
  float bx = p.x * (1.0 - d);

  float r = 0.05 / abs(p.y + sin((rx + time) * xScale) * yScale);
  float g = 0.05 / abs(p.y + sin((gx + time) * xScale) * yScale);
  float b = 0.05 / abs(p.y + sin((bx + time) * xScale) * yScale);
  
  gl_FragColor = vec4(r, g, b, 1.0);
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r124/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>

My CSS:

#webgl-canvas{
  width: 20% !important;
  height:10% !important;
  background: null !important;
}

My JS:

class Stage {
  constructor() {
    //...
  }

  init() {
    //...
  }

  _setScene() {
    //...
  }

  _setRender() {
    //...
  }

  _setCamera() {
    //...
  }

  _render() {
    //...
  }

  onResize() {
    //...
  }

  onRaf() {
    //...
  }
}

//...continued script

Answer №1

To enable alpha support using the WebGLRenderer in three.js, you must activate its alpha buffer by setting the alpha option to true during initialization.

this.renderer = new THREE.WebGLRenderer({
    alpha: true,
    canvas: document.getElementById("webgl-canvas")
});

When using a RawShaderMaterial, the opacity of your texture's pixels is determined by the fragment shader.

If we examine it:

gl_FragColor = vec4(r, g, b, 1.0);

We see that all pixels are opaque regardless of their color. Therefore, any alpha calculations need to be done within the fragment shader. One approach is to use a threshold - for example, if the sum of red, green, and blue is less than 0.5, make it completely transparent.

float a = 1.0;
if (r + g + b < 0.5) {
    a = 0.0;
}
gl_FragColor = vec4(r, g, b, a);

In addition, you should remove your custom clear color:

this.renderer.setClearColor(new THREE.Color(this.renderParam.clearColor));

and add the extra options transparent: true, opacity: 1 to your RawShaderMaterial.

Here is an example:

[example code snippet provided]

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

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Looking to change the input field names by increasing or decreasing when clicking on a div using jQuery?

As a beginner in the world of jQuery, I am working on mastering some basic concepts. Currently, my goal is to create auto incrementing/decrementing input field names within a 'div' when clicking on an add/remove button. Below is the HTML code I a ...

A guide on displaying an array object in a table column using Vue.js and Element UI

Having issues with rendering array data in Vue Js Element UI using the el-table-column element. The string data displays correctly, but I'm facing problems with the array data. I've attempted to include static data within the data() return method ...

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Custom override of SX prop classes with Material-UI theme

I am currently working on customizing a component using the sx MUI prop. <Typography variant='h1' align='center' sx={{ fontSize: '24px', pb: '8px', fontWeight: '700' }} > ...

CompletePage script, individual automatic scrolling

Having trouble with my fullPage.js implementation. I have a total of 5 sections and I'm trying to set different scrolling behaviors for each section. Specifically, I want Sections 1 through 3 to auto-scroll and Section 4.1 to 4.2 to use normal scroll. ...

I am currently facing an issue where the code provided in the Puppeteer documentation is not functioning correctly due to an Un

I followed the code example on the Puppeteer documentation website but unfortunately, it's not working for me. I have Puppeteer 3.0.0 installed via npm. const puppeteer = require('puppeteer'); (async () => { const browser = await pup ...

The bottom border of the check boxes is not displaying in Internet Explorer

https://i.stack.imgur.com/EAkMC.pnghttps://i.stack.imgur.com/ysU1R.png While the checkboxes function correctly in Chrome, they are experiencing issues in Internet Explorer. Below is the HTML code being used: <div class="patient-div-w" style="width: 9 ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Limit the option to check or uncheck all on the current page only

I am facing an issue with a select all checkbox that interacts with checkboxes in a paginated table. The problem arises when I check the select all box, as it selects all records instead of just those on the current page. For example, if there are 200 reco ...

Using JavaScript to assign one object to another object

I am facing an issue where I am trying to assign the local variable UgcItems to uploadedItems, but when I attempt to return the value, it shows as undefined. If I place the console.log inside the .getJSON function, then I get the expected value. However, t ...

How can we show pictures when a user clicks?

After creating a model for displaying images in a modal when clicked by the user, I encountered an issue. Whenever I try to access the images from the gallery within the modal content, it only displays a blank popup. I want the pictures from the image gall ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

Using Three.js to load an image from a different domain

Despite searching extensively and reading through all available resources, I am unable to find a solution to my issue. I am currently running this code on a local server (IIS). My objective is to load an image from imgur and utilize it as a texture for an ...