Issue with Transparency in Background Loading of FBX Files using Three.js

I am currently exploring three.js and have encountered an issue with transparency not working as expected. Despite trying various settings, I cannot seem to achieve a transparent background - it always defaults to black or interprets the values as an RGB value. I've experimented with different configurations based on recommendations from other users:

scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000, 0); (This line seems to be treated as an RGB value?)
scene.background = null;

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

The FBX file is loaded within an iframe, and I have verified the transparency settings on the iframe. Can anyone provide some insight into this issue?

When the transparent call is made, the initial code looks like this...


import * as THREE from '../build/three.module.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { FBXLoader } from './jsm/loaders/FBXLoader.js';

var container, controls;
var camera, scene, renderer, light;

var clock = new THREE.Clock();

var mixer;

init();
animate();

function init() {

    container = document.createElement('div');
    document.body.appendChild(container);

    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(500, 10, 500);

    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x000000, 0);
    scene.background = null;

Answer №1

Issue resolved! Instead of overthinking the solution, I realized I just needed to make a simple adjustment (DUH! *facepalm*). Initially, I mistakenly set the background css on the iframe as:

background:#;

when it should have been:

background-color:rgba(0,0,0,0);

I had actually made this change earlier, but it didn't reflect because the css was cached.

Big thank you to user manthrax for providing assistance and apologies for wasting your time. I'll now quietly retreat for a bit.

Answer №2

Perhaps consider avoiding setting the background color altogether?

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}
body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 2;
  pointer-events: none;
}
#content {
  font-size: 7vw;
  font-family: sans-serif;
  text-align: center;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="content">
  <div>
    <h1>Cubes-R-Us!</h1>
    <p>We make the best cubes!</p>
  </div>
</div>
<canvas id="c"></canvas>
  
<script type="module">
// Three.js - Transparent Canvas
// from https://threejsfundamentals.org/threejs/threejs-tips-transparent-canvas.html

import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({
    canvas,
    alpha: true,
    premultipliedAlpha: false,
  });

  const fov = 75;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 5;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 2;

  const scene = new THREE.Scene();

  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(-1, 2, 4);
    scene.add(light);
  }

  const boxWidth = 1;
  const boxHeight = 1;
  const boxDepth = 1;
  const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

  function makeInstance(geometry, color, x) {
    const material = new THREE.MeshPhongMaterial({
      color,
    });

    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    cube.position.x = x;

    return cube;
  }

  const cubes = [
    makeInstance(geometry, 0x44aa88,  0),
    makeInstance(geometry, 0x8844aa, -2),
    makeInstance(geometry, 0xaa8844,  2),
  ];

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  function render(time) {
    time *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    cubes.forEach((cube, ndx) => {
      const speed = 1 + ndx * .1;
      const rot = time * speed;
      cube.rotation.x = rot;
      cube.rotation.y = rot;
    });

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
}

main();
</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

Extract specific nested elements

Looking for assistance with extracting specific nested objects from a series structured like so: data = {"12345":{"value":{"1":"2","3":"4"}}, {"12346":{"value":{"5":"6","7":"8"}}, {"12347":{"value":{"9":"0","11":"22"}} In need of creating a functio ...

Tips for transferring the data from one yform value to another field

Within our online store, some products feature a yForm to consolidate various parts of the product. Is there a straightforward method to automatically transfer the sum field value to another field, such as the product quantity (which does not use yForm)? I ...

What is the best way to trigger a function in my JavaScript code when the console log is opened on my webpage?

I have a requirement to hide the username and password fields in a form from being viewed in the console log. My plan is to listen for the console log event and then remove the values from these fields using jQuery. Any tips on how to achieve this? Thank ...

Displaying an 'undefined' message in a JavaScript alert box

Hello! Just made the switch from C#/C++ to JavaScript recently and I'm really enjoying it. I've encountered a behavior that has me scratching my head, can anyone help explain? So here's what's happening: when I run this script, I see ...

How do three buttons display identical content?

I have three buttons on my website, each with its own unique content that should display in a modal when clicked. However, I am experiencing an issue where regardless of which button I click, the same content from the last button added is displayed in the ...

Discovering the data from a JSON serialization in JavaScript

Within my PrintViewModel list, there is a sublist called Summary. I am working with ASP.NET MVC. @model CRC.Models.PrintViewModel; <label id="lblTotalMonthlyLoanDeduction"></label> I am serializing it using JSON. var obj = @Json.Se ...

Tips for passing multiple parameters to Web API controller methods in Angular 4

Want to learn how to use Spring Rest Api: @RequestMapping(value={"/save-userlist"}, method=RequestMethod.POST) public ResponseEntity<?> saveUserList(@RequestBody UserListDTO userListDTO, @RequestBody List<User> users, @RequestParam Integer ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Invoking a function from the main window within a child window specified in Angular

This issue is really frustrating me and I've been stuck on it for hours without finding a solution. I'm hoping someone here can help me out. Inside my controller.js file, I have a controller that contains all the information about my page. There ...

Extension Overlay for Chrome

I'm currently working on developing a Chrome extension, but I'm encountering some confusion along the way. Despite researching online, I keep receiving conflicting advice and haven't been able to successfully implement any solutions. That&ap ...

Exploring AngularJS routing integration with Rails

I have recently started incorporating AngularJS into my Rails application. However, I am facing an issue where my route providers with Angular are not functioning as expected. Instead of displaying my template, the Rails view is being displayed. routes.rb ...

Adding a new row to a Bootstrap table while maintaining the consistent style

Is there a way to dynamically add a new table row with different styling using jQuery? I'm facing this particular issue and need help in solving it. Below, I have included some screenshots of my code and the view for better understanding. Here is the ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Managing active dropdown menus in VueJS

I'm having trouble figuring out why my navigation menu and method to open subitems on click are not working correctly. [![dropdown_menu][1]][1] new Vue({ el: '#app', data: { //menu "menu_title": "a", "child_ro ...

What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given. export class CategoryIconComponent extends React.Component { static displayName = 'CategoryIcon'; state = ...

Using PHP to set an array value as a closure for a JavaScript function: Is it possible?

Currently, I am working on creating a custom renderer for the handsontable plugin in my PHP project. To achieve this, I have prepared a set of parameters as a PHP array: $options = [ 'data' => $orders, 'columns' => [ ...

What is the most effective method for creating unit testing functions in JavaScript?

When it comes to JavaScript, there are multiple ways to write the same functions. For example, consider the following options. Which approach is ideal for unit testing scenarios? // Option 1 ============ var app = {}; app.name = "abc" app.init = funct ...

Unlocking route access through server-side Firebase authentication

I have integrated sessionStorage and firebase authentication for user email and password in my project. Currently, I am facing an issue in my server.js where I need to prevent access to a route if the user is not logged in, and instead redirect them to th ...

Attempting to dynamically insert a new row into a table using jQuery, with the added condition of limiting the total number of rows to four

I'm facing an issue with a table that has no rows. I want to dynamically add rows by clicking an anchor tag, with a limit of 4 rows. When the limit is reached, I need to display an alert message saying "only 4 rows allowed." However, currently, it kee ...

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...