Three.js is failing to render within a specified div

My current project involves utilizing three.js to create a cube rendering. Despite the cube appearing on the screen, I am facing issues with getting it to display within the specified div element and in the desired style.

HTML:

<div id="render">

<script>
var camera;
var scene;
var renderer;
var mesh;
var geometry;
var material1;
var material2;
var material3;
var material4;
var material5;
var material6;
var materials;
var meshFaceMaterial;



init();
animate();

function inicio(){
                    Render.setSize(Ancho,Alto);

                    document.getElementById('render').appendChild(Render.domElement);

                    Camara.position.z=1500;

                    Escenario.add(Camara);

                    crear_plano();

                    controls=new THREE.OrbitControls(Camara,Render.domElement);
            }

function init() {


    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 1000);

    var light = new THREE.DirectionalLight( 0xffffff );
    light.position.set( 0, 1, 1 ).normalize();
    scene.add(light);

    geometry = new THREE.CubeGeometry( 10, 10, 10);
    material1 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );
    material2 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );
    material3 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );
    material4 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );
    material5 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );
    material6 = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('http://vignette1.wikia.nocookie.net/scifiminibuilders/images/8/88/Your_Picture_Here.png/revision/latest?cb=20130507015051') } );

    materials = [material1, material2, material3, material4, material5, material6];

    meshFaceMaterial = new THREE.MeshFaceMaterial( materials );

    mesh = new THREE.Mesh(geometry, meshFaceMaterial );
    mesh.position.z = -50;
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

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

    render();
}

function animate() {
    mesh.rotation.x += .015;
    mesh.rotation.y += .015;
    mesh.rotation.y += .015;

    render();
    requestAnimationFrame( animate );
}

function render() {
    renderer.render( scene, camera );
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}
</script>
</div>

CSS:

#render {
    width: 200px;
    height: 200px;
    border: 1px solid black;
    padding: 0px;
}

I'm currently troubleshooting why the cube isn't displaying as expected. Additionally, I'm exploring options for moving the script to an external file. Unfortunately, the code snippet

document.addEventListener('DOMContentLoaded', function() { function _(variable) { console.log(variable); }
doesn't seem to work. Seeking guidance from those more experienced in this area...

Answer №1

Make sure you are attaching the renderer to the correct element on the page:

document.body.appendChild(...)

Instead of adding it to the body, attach it to the specified div like this:

document.getElementById('render').appendChild( renderer.domElement );

To fully grasp your code, try analyzing each line rather than just copying and pasting it.

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

Guide to using AJAX for the GraphHopper Matrix API

I am struggling to send this JSON with the required information because I keep encountering an error during the request. message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8" status: "finished" I'm not sure what I&apos ...

Issues with PHP not properly accepting JSON data sent via Ajaxor

I've been attempting to send JSON data to a PHP file using Ajax. Here is the JavaScript code I've written: function updateJSON(){ var xmlhttpa; if (window.XMLHttpRequest){ xmlhttpa = new XMLHttpRequest(); } else { xml ...

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

The special $ character in angularjs does not seem to be effective in filtering by object

Angularjs documentation states that the filter method should be able to accept an object as a parameter. This object allows you to specify the column to filter by, or use the special character "$" to search through all properties. While the filter works ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

What is the best way to horizontally align my div content while ensuring it is responsive, alongside a sidebar and top menu on the same

I am facing an issue trying to center my div content responsively with a sidebar menu and a top menu using Bootstrap. However, when I require the side-menu file, my div content gets placed at the bottom of the page unexpectedly. I am only using Bootstrap 5 ...

"Triggering the jQuery mouseout event following a resize of an element

I'm currently trying to develop a dynamic shopping cart widget. The concept is to have a box that displays the number of items in your cart, and when you click on it, it expands to show a detailed view of the cart contents. I've successfully man ...

Enhancing FileUpload functionality in ASP.NET with jQuery function prior to postback

My webpage is built with .aspx and contains the following code: .. <form id="frm" runat="server"> <asp:FileUpload runat="server" id="fileupload" onchange="browsed()" /> <asp:Button runat="server" OnClick="Upload_Click" id="uploadb ...

Adjusting the size of images in a Bootstrap lightbox gallery

I am currently working on a website for an artist, making the galleries a key aspect. The website is built using Bootstrap, with the Lightbox for Bootstrap plugin being used for the galleries. Everything seems to be working well in terms of adjusting the i ...

Tips for creating a dynamic menu with animated effects

Check out my fiddle here: http://jsfiddle.net/k3AHM/23/ $(document).scroll(function () { var y = $(this).scrollTop(); if (y > 110) { $('.menu-container').addClass( "fix-menu" ).animate('top', '-3px&a ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...

Convert an array into a query string parameter

Currently, I am refactoring some code and attempting to replace the generation of query strings through concatenation with serializing a JSON object. Original Code: $.ajax({ url:'./services/DataService/getDetails?metric=9&'+dashBoards.g ...

Is there a way to install files that the Bower maintainer has purposely ignored in the configuration?

I am currently utilizing three.js from the repository located at this link. There are some beneficial files within the examples/ directory that I would like to incorporate into my project. Unfortunately, the three.js bower.json configuration file has liste ...

Setting up multiple RabbitMQ or other backend servers within Node configurations

As someone working in DevOps, I have encountered a situation where our developers are claiming that the Node.js software they wrote can only point to a single backend server due to Node.js limitations. This assertion seems unbelievable to me. How is it eve ...

How can Vue be used to dynamically alter a string within an input field by incorporating the status of checked checkboxes?

Yesterday, I stumbled upon a concise Vue presentation on YouTube before answering a technical question on Stack Overflow. The question involved generating checkbox elements based on a string of text containing '1's and '0's, with the ch ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

Issues arise with req.body being undefined when using node.js in conjunction with Express version 4.16.X and Body-Parser version

Recently, I began using node.js to construct a RESTFul API. Currently, my focus lies in inserting data through POST requests with JSON in the body. However, I encountered an issue where the req.body always returned as undefined. Upon investigating further ...

Ensure that the background div extends all the way to the bottom of the page

Is there a clever CSS technique that allows a div to extend all the way to the bottom of the screen without displaying any visible content inside? Or am I better off using JavaScript for this purpose? Thank you, Richard ...

Steps for using selenium to select a radio button

Looking to leverage Selenium in Python 3.9 for button clicking automation. Link to the website https://i.stack.imgur.com/KWsKG.png The goal is to click on "Effective Date", then select "July 2021", and finally click "OK". Initially, the first two steps ...