I am seeking to incorporate several Three.js animations into my HTML document, but I am experiencing issues with them

As a professional graphic designer, I am facing an issue with Three.js

https://i.sstatic.net/6ZsWa.jpg

I have tried several solutions, but none seem to work effectively. In my attempt, I duplicated the imported model and changed its name. Despite trying various methods found online, they all result in overlap, further complicated by having two different names. Below is my .js code:

var container, stats;
        var camera, scene, renderer;
        var mouseX = 0, mouseY = 0;
        var windowHalfX = window.innerWidth / 4;
        var windowHalfY = window.innerHeight / 4;

// Initial setup
init();
animate();

function init() {
	container = document.getElementById('container1');
	document.body.appendChild(container);
	
	camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
	camera.position.z = 4;
	
	scene = new THREE.Scene();
	
	var ambient = new THREE.AmbientLight(0x444444);
	scene.add(ambient);
	
	var directionalLight = new THREE.DirectionalLight(0xffeedd);
	directionalLight.position.set(0, 1, 1).normalize();
	scene.add(directionalLight);

	scene.background = new THREE.Color(0xffffff);

	var objectLoader = new THREE.ObjectLoader();
	objectLoader.load("untitled-scene.json", function (obj) {
		scene.add(obj);
	});
				
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(400, 200);
	container.appendChild(renderer.domElement);

	document.addEventListener('mousemove', onDocumentMouseMove, false);
	window.addEventListener('resize', onWindowResize, false);
}

container = document.getElementById('container2');
document.body.appendChild(container);

camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.z = 4;

scene = new THREE.Scene();

var ambient = new THREE.AmbientLight(0x444444);
scene.add(ambient);

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

scene.background = new THREE.Color(0xffffff);

var objectLoader = new THREE.ObjectLoader();
objectLoader.load("untitled-scene2.json", function (obj) {
	scene.add(obj);
});

renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 200);
container.appendChild(renderer.domElement);

document.addEventListener('mousemove', onDocumentMouseMove, false);

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

function onWindowResize() {
	windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;
    
	camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(canvas_width, canvas_height);
}

function onDocumentMouseMove(event) {
	mouseX = (event.clientX - windowHalfX) / 16;
    mouseY = (event.clientY - windowHalfY) / 16;
}

function animate() {
	requestAnimationFrame(animate);
	render();
}

function render() {
	camera.position.x += (mouseX - camera.position.x) * .03;
    camera.position.y += (- mouseY - camera.position.y) * .03;
    
    camera.lookAt(scene.position);
    renderer.render(scene, camera);
}

Here's the accompanying HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>My Fun Project</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            /* CSS styles */
        </style>
    </head>

    <body>
        <div id="info">
            My Fun Project
        </div>
        
        <div id="container1">
            <script src="num1.js"></script><br/>
        	<script src="three.js"></script>
        	<script src="Detector.js"></script>
        	<script src="stats.min.js"></script>
        </div>
        
        <div id="container2">
        	<script src="num1.js"></script><br/>
        	<script src="three.js"></script>
        	<script src="Detector.js"></script>
        	<script src="stats.min.js"></script>
        </div>
    </body>
</html>

This project is meant for fun, but if you'd like to collaborate, feel free to reach out!

Answer №1

Modification required:

renderer.setSize( 400, 200 );

Change it to:

renderer.setSize( 300, 200 );

Your div is set at dimensions (300,200) but you are rendering other dimensions (400,200), causing your canvas to extend beyond the div boundaries. Adjusting this should resolve any css editing issues.

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

Transferring an array from PHP to JavaScript via an Ajax response

Welcome to my first post on stackoverflow. I usually find answers from existing posts, but this time I'm facing a problem that none of the suggested solutions have been able to fix. Currently, I have a JavaScript function that makes an AJAX request t ...

Ways to avoid Parents Click Event from triggering during a Child's (Grandchild's) click event

My parent div has a unique feature where clicking on it reveals one of the child divs, and clicking again toggles the visibility of the child div. Inside this child div, there is a switch toggle that functions as a hidden checkbox. The issue I'm facin ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Controlling the maximum number of components displayed on each row in a loop or map using React

I'm having some trouble with this seemingly simple task and could use some guidance. Any suggestions would be greatly appreciated. Thank you. My Current Situation Currently, I am working with React.js and have an array containing 20 elements. What ...

Is there a way to eliminate the black seam that is visible on my floor mesh that has been separated? I am utilizing A

I recently imported a large .glb file into AFrame. The model has baked textures and the floor is divided into multiple mesh parts for improved resolution. However, I am facing an issue where black seams appear on the separated parts of the floor, only dis ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Utilizing Ajax for Efficiently Updating a Singular Field within a Designated Object

How can I use Ajax to Update a Single Field in a Specific Object? I have a table in my postgres database with numerous records. I am interested in using a jquery Ajax request to update just one field in a particular object within that table. Is it possibl ...

The regex pattern did not match the line of code in the Node.js script

I need help finding a regex pattern that can identify any line of code containing just one reference to a core module. Here is an example: const coreModuleMatches = /'^[var|const]{0,1}[a-z\$\_]{1,}=require([\'|"][assert|fs|path][ ...

Leverage variables in Ajax to retrieve the data of an HTML element

Seeking assistance in converting multiple lines into a single for loop. var optie1 = ""; if($('#form #optie1_check').is(':checked')) { optie1 = $('#form #optie1_naam').val(); } var optie2 = ""; if($('#form #optie2_ch ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Is there a way for me to invoke a different function that is located external to

I am currently in the process of setting up an event that triggers on any change within the form input class. import React, { useState } from "react"; DealerRegistration extends React.Component { state = { business_type : 'd ...

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

Oops! Looks like there was a NotFoundError when trying to execute the 'removeChild' function on React with Flickity

I am currently developing a React application, and I have integrated the 'CategoriesList' component on the HomePage. Everything works fine when I am on the HomePage, but I encountered an error when I navigated to the ProductDetails page using re ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Quarterly Date Selection Tool with jQuery

I attempted to utilize the Quarter datepicker from: http://jsfiddle.net/4mwk0d5L/1/ Every time I execute the code, I encounter this problem: Cannot set property 'qtrs' of undefined. I copied exactly what was in the jsfiddle, and included the sam ...

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

Creating a jquery DataTable from HTML generated by angular $sce can be done by following these steps

I have created an Angular controller that takes data and generates an HTML table from it. The generated table is being displayed on the page. Now, I want to apply jQuery data tables using that scope variable. The variable contains the HTML code of the tabl ...