What is the process for embedding a 3D model using three.js into a specific div on a webpage?

Lately, I've been struggling with a persistent issue. I can't seem to figure out how to integrate my three.js scene into a div on my website. Despite watching numerous YouTube videos and reading countless articles on the topic, I still haven't found a solution. If anyone could provide some guidance or assistance, it would be greatly appreciated.

Below is the code for my three.js scene:

<script src="three.js"></script>
<script type="module" src="GLTFLoader.js"></script>
<script src="OrbitControls.js"></script>
<script type="module">

import {GLTFLoader } from "./GLTFLoader.js"
  
var scene = new THREE.Scene();
scene.background = new THREE.Color(0xd3d2cd)

var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
camera.position.set(1, 0.7, 1);

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

var loader = new GLTFLoader();

var obj;
loader.load("model.gltf", function (gltf) { obj = gltf.scene; scene.add(gltf.scene);});


var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();

const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 2);
hemiLight.color.setHSL(197, 71, 73 );
hemiLight.groundColor.setHSL(197, 71, 73);
hemiLight.position.set( 0, 0, 0 );
scene.add( hemiLight );

const dirLight = new THREE.DirectionalLight( 0xfdfbd3, 1);
dirLight.color.setHSL(55, 95, 57);
dirLight.position.set( 0, 1.75, .5 );
dirLight.position.multiplyScalar( 20 );
scene.add( dirLight );


function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controls.update();
}


animate();


</script>

I want to mention that I am relatively new to JavaScript and programming in general. It's only been a few weeks since I started learning these concepts. Any help provided would be highly valued. Additionally, please forgive any errors in my English as it is not my first language.

Thank you. Twyn.

Answer №1

To start, insert a canvas into your HTML document.

<canvas id="displayArea" style="width: 100% "></canvas>

Next, grab the canvas using querySelector or the getElementById method.

var canvas = document.querySelector('displayArea');

Lastly, include this code snippet when setting up your renderer:

const renderer = new THREE.WebGLRenderer({ canvas });

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

What is the best way to access and retrieve object properties in JavaScript?

Hey there! I'm working on a project using React with the React Context API. My main component is App.js, which is a functional component containing the app's logic. Within this component, I've set up state using useState for context: const ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...

"The incredible power of the spread operator in conjunction with EsLint

Is there a way to duplicate an object and modify one of its properties? Here's an example: const initialState = { showTagPanel: false, }; export default function reducerFoo(state = initialState, action) { switch(action.type) { case types.SH ...

Using AngularJS to filter options in a dropdown list and trigger a function with ng-change

I have a dropdown menu that is being formatted using filters to display the text in a certain way. I need to send the selected item's ID value to the controller instead of just the name: <select ng-model="my_field" ...

Ways to unmark the "select all" checkbox when any one of its children is no longer selected

Is there a way to automatically uncheck the "Select All" checkbox when any of its child checkboxes are deselected? In the code snippet provided, the goal is for the "Select All" checkbox to be unchecked if not all child checkboxes are selected. The script ...

What could be causing the .hover function to malfunction and how can I make it so that the .hover function only applies within the corner radius area?

I am attempting to make circles react to my jquery .hover function. Below is the JavaScript code I am using: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

Retrieve the genuine HTML code for a control directly on the client side

My goal is to retrieve the complete HTML text for a control from the client browser. This is important because certain information, especially the "Style," does not appear on the server side. How can I obtain the entire HTML text for a control? ...

Double-clicking with Ajax and JSF after the initial click

When I interact with a dataTable that has a column named DELETE (which is a link) and has a listener attached to it, I experience an issue. After clicking on the link for the first time (click 1), the row gets deleted as expected. However, subsequent click ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Displaying multi-dimensional arrays through the console in JavaScript and showcasing their elements

My array is supposed to have 140 indexes in a single format like this: array:[0-140] //however, it currently appears as: array: [ 0: [0-99], 1: [100-140] ] I've confirmed multiple times that it is just one array of objects. Why is it s ...

Expanding the link directory

I am struggling with accessing the "file.php" in the "folder1" directory from the "site" directory. The href path I'm using is: href = "folder1/file.php" However, it redirects me to: href = "folder1/folder1/file.php" Additionally, when try ...

Internet Explorer not triggering jQuery blur() or focusout() events

Having some issues with my form and event handling when the inputs lose focus. The code is working perfectly in every browser except for Internet Explorer. function formstyle() { var focus = 0; //comentario is the ID of the input $("#comenta ...

What could be causing my object to not be added properly to a select element using JavaScript programmatically?

When it comes to customizing your pizza, the options are endless. From selecting the type of crust to choosing your favorite toppings, every detail matters. One common issue that arises is when changing the crust type affects the available sizes ...

Ways to avoid encoding Unicode characters in JavaScript programming

When I retrieve data from an API, I receive a STRING like this: [ { "reason": "Invalid address", "email": "j\u00c3\u00a9r\u00c3\u00b4mel\u00c3\u00a4ufer@com" }, { "reason": "Invalid address", "email": ...

bottom of the page contains the solution

I am currently working on creating a print stylesheet for my website. On each page, there is a footer that needs to be positioned at the bottom of the printed page, but only if there is a spacing of 30pt between the main content and the footer. In cases wh ...

Do you have any recommendations for a creative CSS method to achieve a full-screen background image?

After searching online and experimenting with different methods, I have yet to discover a solution that suits my needs. My goal is to have the background image on my website centered, filling the entire browser screen, while also being compatible with resp ...

Can Ajax and jQuery be utilized on a webpage in conjunction with a cron job?

These are the steps my page performs: Retrieve an array from a different server (first.php) Parse values using a PHP script Send parsed values using an AJAX call In the next page (second.php) that is called by AJAX, perform MySQL queries If values meet c ...

Struggling to eliminate the underlines from an HTML hyperlink

Can someone help me figure out how to remove the annoying underline link that pops up when hovering over an a element in HTML? I attempted adding a style="text-decoration: none" attribute to the a link, but the underline persists when I hover over the text ...