Display various scenes on separate div elements

I utilized the map function to generate multiple scenes. Within this map function, I established a specific number of div elements (the quantity corresponds to the number of scenes). My inquiry is how can I attach each scene to its respective div.

Upon attempting to render, the initial model (or all others, excluding the last one) briefly appears before disappearing, followed by the final model being displayed. My current understanding leads me to believe that this issue is related to the render function.

However, I am uncertain about the next steps to take. Any assistance on this matter would be greatly appreciated.


let cameraInstance = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
const rendererInstance = new THREE.WebGLRenderer({ alpha: true })
rendererInstance.setSize(300, 200)
const oControl = new OrbitControls(
    cameraInstance,
    rendererInstance.domElement
)

const loaderInstance = new THREE.JSONLoader()

let createSceneInstance = tempInstances.map((tempInstance, i) => {
    let sceneInstance = new THREE.Scene()
    const ambientLight = new THREE.AmbientLight(0x383838)
    sceneInstance.add(ambientLight)

    const spotLight = new THREE.SpotLight(0xffffff)
    spotLight.position.set(300, 300, 300)
    spotLight.intensity = 1
    sceneInstance.add(spotLight)

    let newDiv = document.createElement('div')
    newDiv.id = 'instance' + i
    document.getElementById('instances').appendChild(newDiv)

    loaderInstance.load(
        path + tempInstance.json3d,
        (geo, mat) => {
            let ins1 = new THREE.Mesh(geo, mat)
            ins1.scale.set(20, 20, 20)
            sceneInstance.add(ins1)

            cameraInstance.position.set(30, 35, 40)
            cameraInstance.lookAt(sceneInstance.position)

            const render = () => {
                requestAnimationFrame(render)
                oControl.update()
                rendererInstance.render(sceneInstance, cameraInstance)
            }

            render()
        }
    )

    return sceneInstance
})

document
    .getElementById('instance0')
    .appendChild(rendererInstance.domElement)

Answer №1

To ensure each scene has its own unique perspective, it is essential to assign a separate Camera and OrbitControls to each one. While it is possible to share these components among scenes, doing so will result in all scenes rendering from the same viewpoint, which may not align with your intentions.

The WebGLRenderer independently creates its own canvas element (referred to as domElement), meaning you must attach each one to your div like this: div.appendChild(renderer.domElement).

Creating renderers for multiple divs can be resource-intensive if there are many of them...

In this scenario, consider utilizing one Renderer for the entire window (containing a div sized accordingly) and manage it to render solely within specific sub-div areas of the window. However, implementing this approach requires some additional effort:

https://threejs.org/examples/webgl_multiple_elements.html

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

Leveraging Async/Await in NodeJS within Array.map alongside an 'if' condition

Within my code, there is a recursive function that iterates over an object. It specifically searches for keys labeled subcomponent (always containing an array) and executes an asynchronous task on each child within subcomponent, using the output to replace ...

Protecting a Web Function

Suppose I have a C# MVC method to send emails using AJAX, like this: public class EmailController : Controller { SmtpClient mailserver = new SmtpClient("smtp.foo.com"); public string sendEmail(string from, string to, string subject = "", ...

Retrieve the file name of the webpage from the URL bar

Is there a way to retrieve the page name from the address bar using jquery or javascript instead of PHP? I am working on an HTML website and would prefer not to use PHP for this specific task. For example, if the address is www.mywebsite.com/hello.htm, ho ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

retrieve a document from a web server and save it to a mongoDB collection

Our team was tasked with uploading image files to a web server using JavaScript on the client side and Node.js on the server side. The challenge we face is directing the image from the web server to the MongoDB database, where each uploaded file is assig ...

Tips for creating a validator function in Angular that only allows whole numbers between 0 and 30, excluding decimals

When a user enters a value between 0 and 30, the input should accept whole numbers like 0, 2, or 20 but not decimal values such as 20.1 or 0.1. I tried using validators min(0) and max(30), but they still allow decimal values. I need a validator that restr ...

AngularFire Google OAuth failing to retrieve the user's email address

I am trying to retrieve the email address from Google OAuth using AngularFire, but the popup is not requesting permission for the email. This code snippet is from the Firebase Google authentication documentation var ref = new Firebase("https://<your-f ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...

What is the most suitable Vue.js component lifecycle for data retrieval?

I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js? ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...

Verifying the outcome of sampling the mongoose

During my research, I encountered a roadblock. I was trying to determine if a value existed in MongoDB db collection documents using Mongoose. I had a function set up to search for a DB entry using findOne. When stripping away the unnecessary parts of the ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Is it possible to utilize npm request multiple times within a single route and showcase the outcomes on a single page?

Is it possible to utilize the node module "request" multiple times within a single route, and have the outcomes presented on a solitary rendered ejs template page? Objective: The aim is to exhibit eBook details from the iTunes Store by utilizing their Sea ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

When a link is clicked, the text within an input field

Seeking a solution for inserting a value into an input when clicking a link, with the inserted value being the name of the clicked link. I am unsure how to achieve this. Can anyone provide guidance? The solution can involve jQuery, JavaScript, PHP, or any ...

Tips for efficiently calling a function without the need to check if it exists beforehand

I'm looking for a way to access the formik props outside of the form without constantly checking if a function exists before calling it when using refs. Any suggestions on how to achieve this? function BasicInfo({ event, initialValues, onSubmi ...

MVC5 Toggle Button for Instant Display and Concealment

I used to utilize this method in Web Form development by targeting the id and name of the input radio button. However, I am encountering difficulties implementing it in MVC5. Can someone kindly point out where I might be going wrong? Upon selecting a radi ...

Animating overlapping div elements using jQuery

I am currently using jQuery's animate() function to adjust the size of a "row", but I am facing an issue with a badge that sometimes appears on the row. The problem is that the badge gets hidden during the animation, which doesn't look good. I ha ...

Utilizing node core modules effectively within webpack configuration

I'm currently facing challenges when developing an express.js app with webpack. It seems like I might not be handling the node.js core module 'http' correctly. Specifically, my package.json is structured like this: { "name": "basic-expre ...