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

Can you actually achieve the creation of an Equilateral responsive triangle with a background image using CSS?

It's important that it works in IE11 as well. I've attempted: Using traditional triangle-creating techniques with borders - Unsuccessful, no background image appeared. Clip-path - Failed, no support in IE Triangles created us ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Having trouble with your Ajax post request?

I am currently working on creating a form that allows users to input information and submit it without the page refreshing. The processing of the form data will occur after the user clicks the submit button. To achieve this, I am utilizing jQuery and Ajax ...

Filtering data based on the model in React Native allows you to refine and organize

This code snippet represents a modal that contains two custom dropdown components, a text input, and a button. When the button is clicked, it filters data from an API. Currently, I am struggling to create a functional filter function despite multiple atte ...

When the window width increases, the image within a flexbox causes the flexbox to break

I'm currently working on designing a responsive splash page that covers most of the page (90vh). The layout includes a logo at the top and a simple paragraph at the bottom. I've experimented with using flex-shrink and flex-basis, but it's n ...

Sorting columns containing English, Japanese entries, and null values using a customized sorting algorithm in MUI Data Grid is a straightforward process

I am working with an MUI data grid and I am looking to implement a custom sorting algorithm for columns that can override the default options provided by MUI. The data in my fields is in English, Japanese, as well as empty/null values. My desired output sh ...

Customize your Shopify Messenger icon using JavaScript!

Shopify recently introduced a new feature that allows customers to contact store owners through messenger. My client has requested me to customize the appearance of this icon with their branded icon instead. https://i.stack.imgur.com/uytpd.png I have not ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

Troubleshooting the Node.js Server Error Encountered when Enabling AngularJS html5Mode(true)

When using routeProvider and stateProvider in AngularJS with HTML5 mode set to true, everything functions correctly until the page is refreshed. On a Node.js server, I am unsure of what needs to be written on the server side to prevent receiving a "Can no ...

Increasing the size of a background image as you scroll

Is there a way to adjust the background image of a div so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image ...

Looking for guidance on implementing throttle with the .hover() function in jQuery?

Seeking a way to efficiently throttle a hover function using jQuery. Despite various examples, none seem to work as intended. The use of $.throttle doesn't throw errors but ends up halting the animation completely. Here is the code snippet in question ...

What steps can I take to prevent BeautifulSoup from interpreting commas as tab characters?

My recent project involved creating a web scraping code to extract information from a local news website. However, I have encountered two issues with the current code. One problem is that when the code retrieves paragraph data and saves it to a CSV file ...

Dynamic animations with RaphaelJS - Creating animated connections

I recently came across a similar project here: My current project involves animating boxes by clicking a button. While I am able to move the boxes around smoothly during animation, the issue is that the connections between them do not move along. Is there ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

Modifying the appearance of radio buttons using jQuery

I'm new to jQuery and I'm finding it challenging. Currently, I have a set of three radio buttons with the third button already prechecked. My aim is to change the CSS class of the checked button, making it similar to an unchecked button with the ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Filtering ng-repeat in AngularJs based on nested data properties

Within my data tracking appointments, I have information on months, weeks, days, and timeslots. When it comes to the listing view, displaying "weeks" is unnecessary (although important for other reports). To eliminate days without appointments, I can use ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

"Learn the steps to enable a click-to-select feature for an item, allowing you to drop it in a different location

I've been spending quite some time trying to come up with a solution for my dilemma. The issue arises because I'm not looking to use drag and drop functionality. https://i.stack.imgur.com/Nh1Db.png My goal is to have 3 divs named 1,2,3 as desig ...