Trouble with displaying THREE.js image on canvas

I have set up two different scenes and renders in my project. In addition, I have utilized Bootstrap 4 for the modal window functionality. One scene serves as the main display, while the other is displayed within the modal window. This is why I am employing two separate renders: one for the element on the main screen and another for the modal window.

Here is the code:

Main scene:

<div class="output3d" id="WebGL-output"></div>

function setMainScene() {
        // Main scene setup goes here
}

Scene for modal window:

<div class="modal" data-backdrop="static" id="ObjectInfo" role="dialog" tabindex="-1">
    <!-- Modal window setup code here -->
</div>
 function setModalWindowScene() {
        // Modal window scene setup goes here
}

Init:

function init() {
    setMainScene()
    setModalWindowScene()

    // Adding objects to main scene
    addRoom()
    addRacks()
    addExtinguishingCylinders()
    addHotHalls()
    addWires()
    addLights()

    window.addEventListener('resize', onWindowResize, false);
}

Rendering:

function animate() {
    requestAnimationFrame(animate);
    render();
}

function render() {
    // Main rendering logic
}

function onWindowResize() {
    // Window resize logic
}

HTML:

<script type="text/javascript">
    init();
    animate();
</script>

One issue that has been encountered is when a user opens the modal window for the first time, the object picture doesn't initially appear. However, upon resizing the window, the picture appears and remains visible. An interesting observation is that even when there is no picture in the modal window, the object can still be rotated using the controls associated with the modal scene.

You can see a demonstration of this issue below: Before resizing After resizing

Answer №1

In order to properly render your scene, it is important to include the render function within your init function.
Simply putting it inside the onWindowResize function will not suffice as this only triggers when the window is resized and not when the page initially loads.
Consider implementing a render loop to continuously update the visuals of your scene.

Refer to the example provided below for guidance.
Notice how the init function sets up the scene and then the animate function kicks off the render loop.

var camera, scene, renderer, mesh, material;
// set up the scene.
init();
// Start the animation/render loop.
animate();

function init() {
    // Set up the renderer.
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // Create the camera.
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 400;

    // Create the scene.
    scene = new THREE.Scene();

    // Prepare the material.
    material = new THREE.MeshPhongMaterial();

    // Generate a cube and add it to the scene.
    var geometry = new THREE.BoxGeometry(200, 200, 200);
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    // Introduce ambient light to the scene.
    var light = new THREE.AmbientLight(0x404040);
    scene.add(light);

    // Add directional light to the scene.
    var directionalLight = new THREE.DirectionalLight(0xffffff);
    directionalLight.position.set(1, 1, 1).normalize();
    scene.add(directionalLight);

    // Listen for window resize event.
    window.addEventListener('resize', onWindowResize, false);

}

function animate() {
    requestAnimationFrame(animate); 
    mesh.rotation.x += 0.005;
    mesh.rotation.y += 0.01;
    renderer.render(scene, camera);
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>

Answer №2

Upon reviewing the situation, it appears that I neglected to specify an aspect ratio when creating the modelWindowCamera because the element

document.getElementById("FrontView")
had no dimensions prior to the initial rendering. However, after adjusting the scale of the window, the element
document.getElementById("FrontView")
was no longer sizeless and the camera's aspect ratio was able to update correctly.

To resolve this issue, I have now set the aspect ratio to a constant value of 1, resulting in the revised code below:

   modalWindowCamera = new THREE.PerspectiveCamera(45, 1, 1, 100);

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

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself? I've attempted it like this but seem to be making a mistake somewhere. ...

Switch between individual highcharts by selecting or deselecting checkboxes

One of the challenges I am facing involves manipulating multiple scatter plots created with highcharts. I have a list of checkboxes, each labeled to correspond with legend identifiers in the highcharts. My goal is to create a dynamic functionality so tha ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

Using type annotations is restricted to TypeScript files only, as indicated by error code ts(8010)

I encountered an issue with React.MouseEvent<HTMLElement> const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => { setAnchorElNav(event.currentTarget); }; const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement ...

Both if and else statements are carrying out code in JavaScript/jQuery

The second if statement is functioning correctly, but the first one always triggers the else statement and never stands alone. This jQuery function is enclosed within another function that is invoked under the "$(document).ready" command. I resorted to u ...

How to send parameters to the jQuery delete button click event handler

Here is the jQuery code I am working with: $('#btnDelete').click( function() {//Do the delete here via jquery post}); In my table, each row has a delete button like this: <a id="btnDelete">Delete</a> I need to pass parameters to t ...

Is it acceptable to reference all JS files in index.html in Angular?

Just dove into my first AngularJS project! Following a tutorial where they put everything in one controller, but now I want to separate controllers and services. I managed to split them into different JS files, but is it best practice to list all these f ...

Associating specific information with individual elements utilizing HTML text box

Seeking guidance on implementing annotations feature for a scatter-plot using d3.js v3. My goal is to show a text-box upon clicking each data point, then display that entered text as a tool-tip specific to that data point. Here's how I'm approach ...

Is there a way to determine if a webpage is being accessed from a website or from a local file system?

While this question has been raised in the past, none of the answers provided seem to be accurate. Unfortunately, I am unable to comment on the original question or answers. Thus, following suggestions given to me, I have decided to create a new question. ...

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...

Is the "json_encode" function dropping the '+' character when using "json.parse"?

Seeking Assistance I have a question regarding the functionality of php function json_encode and js JSON.parse. I seem to be encountering an issue where the '+' character is being dropped somewhere in the process, particularly when dealing with ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

function embedded in velocity.js chain

How can I effectively execute this code? I keep encountering various errors. After the sequence is completed, I want to incorporate an additional function. I am utilizing jQuery in conjunction with velocity.js $(".close").click(function(){ var my ...

convert JSON to Java object using GSON with a map

Here is the structure of my Java POJO: public class MyPersonTO{ String name; String surname; Map<String, Double> categories; } Currently, I am using the Gson library, but I'm uncertain about the formatting of my JSON string and the obje ...

Node.js MongoDB Error: db.open is undefined

I recently started experimenting with MongoDB and encountered an error message stating TypeError: db.open is not a function. Although new mongodb.Server and new mongodb.Db seem to be functioning correctly. The issue arises while using [email protecte ...

Navigating a loop in javascript: tips and techniques

I have a challenge with three boxes that are supposed to fade in, shake, and then fade out. The IDs of each box are stored in an array and a loop is used to traverse them. However, the loop only displays the first item. I have tried various methods in Jav ...

Interacting with a non-stringified object displayed in the browser console using TestCafe

Upon receiving a page that logs an object to the console, I encountered an issue when trying to access this object using getBrowserConsoleMessages(). The object appeared as the String "[object Object]" in the console, making it impossible for me to parse ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

Can we enhance the efficiency of this equation?

The formula provided organizes the elements in the container based on mouse movement. The issue stemmed from the image size and the different calculations performed when approaching along the x and y axes from various directions. const zoomEffect = (even ...