The browser is displaying the scene, but the Three.js Geometry is not visible

After following a tutorial and successfully getting the entire scene to work within the body tag, I decided to move it inside a div. However, now only the scene itself is rendered. Despite not receiving any errors and ensuring everything is accessible through console logs, I can't seem to figure out why nothing is being displayed.

// console.log ("Java Script is working!")

// get div for 3D area
const container = document.querySelector('#container')
// console.log (container)
var scene = new THREE.Scene()

var camera = new THREE.PerspectiveCamera(
  75,
  container.innerWidth / container.innerHeight,
  0.1,
  1000
)
camera.position.z = 3

var renderer = new THREE.WebGLRenderer({
  antialias: true
})
renderer.setClearColor('#0D1033')
renderer.setSize(container.innerWidth, container.innerHeight)

container.appendChild(renderer.domElement)

container.addEventListener('resize', () => {
  renderer.setSize(container.innerWidth, container.innerHeight)
  camera.aspect = container.innerWidth / container.innerHeight
  camera.updateProjectionMatrix()
})


var geometry = new THREE.BoxGeometry(10, 1, 1)
var material = new THREE.MeshLambertMaterial({
  color: 0x90e9f9,
  side: THREE.DoubleSide
})
var mesh = new THREE.Mesh(geometry, material)

scene.add(mesh)


var light = new THREE.PointLight(0xffffff, 5, 500)
light.position.set(10, 0, 25)
scene.add(light)

var render = function() {
  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
console.log(mesh)
console.log(camera)

render()
* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
  height: 100vh;
}

canvas {
  display: block;
  height: 100%;
  width: 100%;
}

#container {
  background-color: black;
  height: 100vh;
}
<!DOCTYPE html>

<body>
  <div id="container">

  </div>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/102/three.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.2/TweenMax.min.js"></script>
  <script src="main.js"></script>
</body>

</html>

Before integrating this into my main project, I'm attempting to troubleshoot and ensure it works independently. My goal is to have a 3D space within a specific div on the website without taking up the entire page.

Answer №1

If you want to access the size of the window, make sure to use the innerWidth and innerHeight properties on the window object. If you need the dimensions of an element, use clientWidth and clientHeight instead:

const container = document.querySelector('#container')

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
  75,
  container.clientWidth / container.clientHeight,
  0.1,
  1000
)
camera.position.z = 3

const renderer = new THREE.WebGLRenderer({
  antialias: true
})
renderer.setClearColor('#0D1033')
renderer.setSize(container.clientWidth, container.clientHeight)

container.appendChild(renderer.domElement)

container.addEventListener('resize', () => {
  renderer.setSize(container.clientWidth, container.clientHeight)
  camera.aspect = container.clientWidth / container.clientHeight
  camera.updateProjectionMatrix()
})


const geometry = new THREE.BoxGeometry(10, 1, 1)
const material = new THREE.MeshLambertMaterial({
  color: 0x90e9f9,
  side: THREE.DoubleSide
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)


const light = new THREE.PointLight(0xffffff, 5, 500)
light.position.set(10, 0, 25)
scene.add(light)

const render = function() {
  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render()
* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
  height: 100vh;
}

canvas {
  display: block;
  height: 100%;
  width: 100%;
}

#container {
  background-color: black;
  height: 100vh;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5819d879090b5c5dbc4c6c6dbc4">[email protected]</a>/build/three.min.js"></script>
<div id="container">

</div>

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

Struggling with routing in Node.js while working on REST API development via HTTP

I am facing an issue while trying to complete a MEAN project. The client side is already done, but I am having trouble with the server side when attempting to make a new insertion (which is carried out using HTTP Post). Below, I will demonstrate how I hav ...

Issue with Vuex causing error message "TypeError: Unable to access property 'getters' of an undefined object"

I am facing an issue where Vuex seems unable to locate my getter for the loading_state. While the vuex state and getter are visible in the Vue developer tools, I am unable to access them within my application. I have attempted to make changes such as mod ...

The act of loading a webpage without inserting any data into the database is not recommended

I've created an enroll.html page with the following code: <HTML> <HEAD> <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></scr ...

Issues encountered when trying to retrieve data from an Express server

I have set up a NodeJS server with Express.js and I am attempting to send a request to it using fetch. fetch("http://localhost:3001/api", { method: "POST", headers: { "Content-Type": "application/json", ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

performing iterations on html code with php

I have a code snippet inside an HTML file that I would like to loop using PHP. The goal is to repeat a paragraph on my HTML page as many times as needed. Any assistance with this would be greatly appreciated. <?php for($i=0;$i<=5;$i++){ <li ...

Is there a way to use an Angular $watch to determine the specific changes made to $scope.value?

I am monitoring a variable called $scope.value with a watch in my code. There are two ways in which the value can be updated: The first is by updating it from the controller, such as through any services. The second way is that any input event can also ...

Explore how Vue 2.1 allows for the dynamic updating of dropdown options based on selections made in another dropdown

Currently, I have a Vue v.2 form set up with an address section that includes a State dropdown. My goal is to make the State dropdown automatically populate based on the city selected. For example, if a user chooses 'Atlanta' as the city, 'G ...

PHP's $_SESSION variable for passing data between pages

Every time I visit a new page, whether it's a login page or any other, I want to store the name of that page in a $_SESSION variable. For example, on the login page: <?php session_start(); $_SESSION['page'] = 'login.htm&apo ...

What are the steps to utilize the `<script setup>` feature?

Vue version: 3.0.11 Here is the code snippet: <template> <button @click="inc">{{ count }}</button> </template> <script setup> import { ref } from 'vue' export const count = ref(0) export const i ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

Customizable Data Tables for Users

In my project, I am utilizing the Datatable library to display a table with 20-25 columns. Is there a feature in Datatable that allows users to customize which columns they want to hide and display? Here is how I have set up my Datatable: $("#datatable-b ...

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

Position of fixed div set relative to its parent fixed div

I'm facing an unusual situation where I need a fixed div to be positioned relative to its parent, which is also a fixed div. When you take a look at my example, everything will become clear. <div class="drawer"> <p>Drawer</p> & ...

Dynamic components in Angular and the error of ExpressionChangedAfterItHasBeenChecked

Seeking to create a versatile component that can dynamically contain various components. The objective is to compose an article with the flexibility of including either paragraphs or tweets. The following code defines DynamicArticleComponent: @Directive( ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

Struggling with CSS Flexbox when it comes to organizing rows and combining Table and Table Cells

I've been struggling to fix a CSS flex problem for hours. My goal is to make sure that the three boxes in each row have the same height. While I'm familiar with using flex, I suspect that floats may be the root of the issue. Even after clearing t ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Ways to stop users from accidentally changing routes in react router v3

Currently, I am working on creating a custom hook to block users from making unintended route changes like using the back button or refreshing the page. Since I am using react-router v3, the <Prompt /> component in react router v4 is not an option fo ...

What is the proper method for correctly loading assets from a NPM package generated by webpack?

Currently, I am using webpack to create the necessary files for an npm package that will contain a selection of react components. These components include CSS that links to various fonts and icons. However, when employing the file loader, these assets are ...