Display a dynamic creation of a "object/canvas" utilizing Three.js embedded within a DIV element

Check out this Code:

I have a dynamic "object" created in Canvas using Three.js, but it's currently appearing at the bottom of the page, just before the closing </body> tag. How can I adjust its position so that it loads inside the "

<div id="container"></div>
" div instead?

Take a look at my code:

HTML:

<div id="container"></div>

JS

 // revolutions per second
 var angularSpeed = 0.2;
 var lastTime = 0;

 // function executed on each animation frame
 function animate() {
     // update
     var time = (new Date()).getTime();
     var timeDiff = time - lastTime;
     var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
     cube.rotation.y += angleChange;
     lastTime = time;

     // render
     renderer.render(scene, camera);

     // request new frame
     requestAnimationFrame(function () {
         animate();
     });
 }

 // renderer
 var renderer = new THREE.WebGLRenderer();
 renderer.setSize(window.innerWidth, window.innerHeight);
 document.getElementById("container").appendChild(renderer.domElement); // add renderer to container

 // camera
 var camera = new THREE.PerspectiveCamera(120, window.innerWidth / window.innerHeight, 1, 1000);
 camera.position.z = 700;

 // scene
 var scene = new THREE.Scene();

 // create cube (Length, Height, Width)
 var cube = new THREE.Mesh(new THREE.CubeGeometry(400, 200, 200), new THREE.MeshNormalMaterial());
 scene.add(cube);

 // start animation
 animate();

FIDDLE for reference: http://jsfiddle.net/6a7u4/1/

If you require more information or have any suggestions, feel free to let me know.

Please share your thoughts.

Answer №1

My best guess is

document.body.appendChild(renderer.domElement);

needs to be changed to

document.getElementById("container").appendChild(renderer.domElement);

Update: To ensure proper functionality, I have also adjusted the size to dynamically get its height/width from the container div. The updated rendering code now looks like this.

// renderer
var container = document.getElementById("container");
var renderer = new THREE.WebGLRenderer();
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(renderer.domElement);

See the result on Jsfiddle: http://jsfiddle.net/6a7u4/2/

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

Creating unique identifiers/primary keys for resources in react-admin: A step-by-step guide

I am working on a nextJS project that utilizes redux for state management and an admin panel called react admin. In my project, I decided to use _id instead of id as the keys. To achieve this, I followed the instructions provided in this custom identifiers ...

Display Google Maps and YouTube videos once user consents to cookies

I recently installed a plugin on my WordPress site called Cookie Notice, which I found at this link. So far, I've been impressed with how user-friendly and lightweight it is. Due to the latest GDPR regulations, I now need to figure out a way to hide ...

Toggle antialiasing and shadows on the fly in WebGLRenderer

Is there a way to dynamically enable or disable antialiasing and shadows in WebGLRenderer? Simply adjusting anti-aliasing and shadowMapEnable properties doesn't seem to do the trick. I delved into the source code and stumbled upon the method updateSh ...

What are the implications of implementing Ajax without relying on jQuery?

At a stage where I require Ajax on my webpage, but only for a specific section - checking if a username is present in the database. As detailed here, Ajax can be implemented using just JavaScript. What are the advantages and disadvantages of opting for t ...

When I press the single quote, the submit button becomes disabled and stops working

image: https://i.sstatic.net/nKCTk.jpg result: https://i.sstatic.net/PE4oN.jpg When I press the '(single quote) key on my keyboard, the submit button (reply button) is not being disabled as expected. I simply want it to be disabled in order to pre ...

Pass the initial value from a parent component to a child component in ReactJS without the need for state management

Initially, I have a parent Component A that calculates an initial value for its child Component B. The initial value is computed in the componentDidMount() of Component A and passed to B using props: <ComponentB initialValue={this.state.value} handleCha ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

Tips for dynamically inserting a new column into a table at any position other than the beginning or end

I have created a dynamic table where rows and columns can be added dynamically. However, I am facing an issue where I am unable to add a new column between the first and last column of the table. Currently, new columns are only being added at the end. $ ...

Using Javascript to trigger an event when an option is changed in an ASP dropdownlist

Can someone provide me with sample javascript code that can be used to determine if an item has been selected in a dropdown list and then make it visible? ...

strange SQL issue and JavaScript AJAX problem

In my database, there is a basic table setup as follows: $start = //correct $end = //correct $query = ' SELECT id, title, start_in, duration, color, DATE_ADD( start_in , INTERVAL (duration*60) MINUTE ) AS end_in FROM shifts ...

I am interested in creating a text box that has the ability to gather user input and connect it to a search

I have been attempting to develop a text box that can collect answers and link them with the search URL. However, I am encountering issues where even though I can input text into the textbox, it is not being recognized by the script. The error message sh ...

What is the method for gaining access to variables and functions within bundle.js?

Hello, I am trying to figure out how to access variables in bundle.js. I want to experiment with variables and functions on the client side using JavaScript, but I'm having trouble calling them in index.html or the Chrome console. I use browserify to ...

Is it possible to have content in an array with a length of 0?

Here is the test code that I am using: console.log('AA',slider); console.log('AB',slider.length); When I check the Chrome console, it shows the following results. AA Array[53] AB 0 I included this test code because even though there ...

Error Loading Collada Texture: Three.js Cross Origin Issue

I'm encountering an issue with loading a Collada file using three.js that has a texture called Texture_0.png associated with it. The Collada file and the texture are stored in the same blob and accessed via a REST Web Service. CORS is enabled, allowin ...

Creating an array to store multiple ID values within a variable

const idArray = $scope.rep.Selected.id; I am working with this piece of code. I am wondering, if I have multiple ids in the $scope...Selected.id and then execute this (code), will all these ids be placed in separate arrays or combined into one array? ...

The Codeigniter ajax call fails to function properly when an external JavaScript file is incorporated

Why does my Codeigniter ajax request work when JS is embedded internally, but not when I try to use it as an external JS file? View the code for the sample_ajax below: <html> <head> <title></title> <scrip ...

Transform a string into a variable

When receiving JSON data from AJAX, I often find myself working with multiple variables. For example, I may have data stored in variables like data.output_data_1234 and data.output_data_5678. To work with these variables more effectively, I convert them t ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload(). I've tried numerous approaches, but none seem to be working for me. Below is the code I've been working wit ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...