CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class.

I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? Thank you in advance.

import {
    Scene,
    Color,
    Vector3,
    AxesHelper,
    PerspectiveCamera,
    WebGLRenderer,
    DirectionalLight,
    HemisphereLight,
    AmbientLight,
    sRGBEncoding
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer.js";
// import Stats from 'three/examples/jsm/libs/stats.module.js';

export default class SceneCreator {
    /**
     * 
     * @param {*} container 
     */
    constructor(container) { 
        this.container = container;
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.css_renderer = new CSS2DRenderer();
        // this.stats = new Stats();
        this.initScene();
    };

    initScene=()=> { 
        this.scene = new Scene();
        this.scene.background = new Color(0x21252d);

        this.createCamera();
        this.createLights();
        this.createControls();
        this.createRenderer();
        this.createAxe();
        // this.container.appendChild(this.stats.dom);
        this.renderer.setAnimationLoop(() => {
            this.renderer.render(this.scene, this.camera);
            this.css_renderer.render(this.scene, this.camera);
            // this.stats.update();
        });

        this.css_renderer.setSize( this.container.clientWidth, this.container.clientHeight );
        this.css_renderer.domElement.style.position = 'absolute';
        this.css_renderer.domElement.style.top = '0px';
        this.container.appendChild(this.css_renderer.domElement);
        
        window.addEventListener("resize", this.onWindowResize, false);
    }

    createCamera=()=> { 
        const fov = 60; 
        const near = 1;
        const far = 1000;
        const aspect_ratio = this.container.clientWidth/this.container.clientHeight
        this.camera = new PerspectiveCamera(fov, aspect_ratio, near, far);
        this.camera.position.set(0.1, 10, 10);
        this.camera.lookAt(0, 0, 0);
    }

    createControls=()=> {
        /* Create Controls to allow for scene control */
        // const controls = new OrbitControls(this.camera, this.container);
        const controls = new OrbitControls( this.camera, this.css_renderer.domElement );
        controls.update();
    }

    createLights= ()=> {
        const mainLight = new DirectionalLight(0xffffff, 5);
        mainLight.position.set(10, 10, 10);

        const hemisphereLight = new HemisphereLight(0xddeeff, 0x202020, 5);
        const ambientLight = new AmbientLight(0x404040, 5);

        this.scene.add(mainLight, hemisphereLight, ambientLight);
    }

    createAxe = (len=1.6, pos=null) => { 
        const axis = new AxesHelper(len);

        const red   = new Color(0xff0000);
        const green = new Color(0x00ff00);
        const blue  = new Color(0x0000ff);
        
        axis.setColors(green, blue, red);

        if (pos === null) { 
            pos = new Vector3(8.0, 5.0, -3.2);
        }
        axis.position.x = pos.x;
        axis.position.y = pos.y;
        axis.position.z = pos.z;
       
        this.scene.add(axis);
    }
    createRenderer = ()=> {
        this.renderer = new WebGLRenderer('webgl2',{ antialias: true, alpha: true });
        this.renderer.setClearColor( 0xA3A3A3, 0 );
        this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.physicallyCorrectLights = true;
        this.renderer.outputEncoding = sRGBEncoding;
        this.container.appendChild(this.renderer.domElement);
    }

    onWindowResize = ()=> {
        this.camera.aspect = this.container.clientWidth / this.container.clientHeight;
    
        // Update camera frustum
        this.camera.updateProjectionMatrix();
    
        this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
        this.css_renderer.setSize(this.container.clientWidth, this.container.clientHeight);
    }

    getScene = () => { 
        return this.scene;
    }

    getCamera = () => { 
        return this.camera;
    }

    getRenderer = () => { 
        return this.renderer;
    }

    getCSS2DRenderer = () => { 
        return this.css_renderer;
    }
}

Answer №1

It seems like you haven't added any CSS2DObject to the scene in your example. I suggest storing the objects you plan to remove in a separate array for easy access later on. Avoid destroying the renderer and rebuilding it, as it will only result in unnecessary complexity.

let allCSSItems = [];

const item1 = new CSS2DObject();
scene.add(item1);
allCSSItems.push(item1);

const item2 = new CSS2DObject();
scene.add(item2);
allCSSItems.push(item2);

// Continue adding more items...

// When you want to remove them from the scene, simply use the array
allCSSItems.forEach((item) => {
    scene.remove(item);
});

// Empty the array
allCSSItems = [];

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

Jquery selector failing to target correct <form> element within Shopify theme

I'm feeling a bit lost here! Trying to zero in on a form within my page and utilize jQuery's serializeArray() function to extract all the values from said form. <div class="page-width"> <header class="section-header ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

When I click the mouse, my drawing function starts lines from the top left corner instead of the latest point

http://codepen.io/FreelanceDev/pen/kLpJSf?editors=1010 You can find my CodePen project through the provided link. While the HTML and CSS elements are working correctly, I am facing issues with the JavaScript functionality. The desired outcome should be d ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Display a badge in the navbar on specific VueJS pages

I have embarked on the journey of creating a single page application using Vue 3, and I've encountered an interesting scenario where I want to display a badge in the navigation bar for specific pages. This is how my setup looks: // App.vue <templat ...

Is it possible to implement an SSL certificate with my Next JS deployment?

Currently, I am running a Next.js deployment on an EC2 instance and looking to secure it with an SSL certificate. My initial thought was to use a custom server config for this purpose, but I'm concerned that it may impact certain optimizations that I& ...

Injecting Javascript before page code in Chrome Extension Content Script allows for manipulation of webpage elements

I am currently working on developing a Chrome extension that involves injecting a script into a webpage before any other scripts present. This is crucial for my project as I am utilizing the xhook library to intercept XHR requests, which necessitates overw ...

I encountered an error with status code 401 despite providing the API token as required

Can anyone help me troubleshoot an issue I'm having with a POST request using VueJS in Laravel? The request keeps failing with a 401 status code, even though I'm passing the token in the headers. const post_data = { headers: { Authoriza ...

Eliminate the legend color border

I have successfully implemented the following code and it is functioning properly. However, I am trying to remove the black boundary color legend but am struggling to figure out how to do so. var marker = new kendo.drawing.Path({ fill: { co ...

Boost the delay in the transition speed for hiding the Navbar while scrolling down with the help of Bootstrap

Hi there! I am currently learning HTML, CSS, and JS. I'm working on a homepage project using Bootstrap-5 and have successfully integrated a navbar. However, I've noticed that the navbar disappears too quickly when I scroll down. Is there a way to ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

The Distinction between Object.assign and the simple assignment operation

Could you please explain the distinction between these two lines of code? Object.assign(otherObject, { someNewProperty: '' }); vs. otherObject.someNewProperty = ''; Also, which one of these methods is more efficient in terms of sp ...

Choose the initial full text that corresponds with a portion of the text

I am currently working on a page with multiple <string> tags containing different strings, like 'Is this a String?  Yes'. My goal is to use JQuery to locate the first instance of 'Is this a String?  ' and extract either ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

Using a combination of ASP.NET webpage and JavaScript, a dynamic webpage with a repe

I am new to using VB and integrating JavaScript. I have a simple question, but I'm having trouble figuring it out for some reason. I am struggling to properly construct an IF-statement. Can you please help me? I have searched and googled, but have no ...

What is the most efficient way to establish a connection to "host:port" without relying on a web browser, utilizing only Node.js/JavaScript?

To establish a connection with a server (created using node js), we simply open the browser and include some code in a file like this: <script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script> <script type="text/javascript">/* ...

Using jQuery to apply a class based on JSON data

This file contains JSON data with details about seat information. var jsonData = { "who": "RSNO", "what": "An American Festival", "when": "2013-02-08 19:30", "where": "User Hall - Main Auditorium", "seats": ["0000000000000000001111111 ...