Creating an event listener in the window object for the three.js

Struggling to create a MyObject.prototype.onWindowResize function for scaling a simple cube on window resize. Can't seem to make it work - either getting undefined or no change at all. Spent hours searching for a solution with no luck. Any help would be greatly appreciated. Thank you in advance.

//OOP THREE 

//Global Variables

var ROTATE_Y = 0.03;

  //Constructor
function Cube() {

    this.width = window.innerWidth,
    this.height = window.innerHeight;

    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera( 70, this.width/this.height, 1, 1000);

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

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

    //var self = this;
   //window.onWindowResize = this.onWindowResize.bind(this);
   //window.addEventListener( 'resize', function(e){this.onWindowResize(e);}.bind(this), false);
    //window.addEventListener( 'resize', this.onWindowResize.bind(this), false);
    //window.addEventListener( 'resize', function (event) {this.onWindowResize(event)}, false);

    this.init();
}

Cube.prototype.init = function () {

    this.light();
    this.box(); 
    this.render();
    this.animate();

}

Cube.prototype.light = function(){

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

}

Cube.prototype.box = function(){

    this.geometry = new THREE.CubeGeometry( 10, 20, 10);
    this.material = new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x0033ff, specular: 0x555555, shininess: 30 } );
   var boxMesh = this.mesh = new THREE.Mesh(this.geometry, this.material);
     this.mesh.position.z = -50;

    boxMesh.rotation.y = ROTATE_Y;

    this.scene.add( this.mesh );

}

Cube.prototype.update = function(number){

    if(number > 0){
        this.mesh.rotation.y += ROTATE_Y;
    }

}

Cube.prototype.animate = function() {

    requestAnimationFrame( this.animate.bind(this) ); 
    this.render();
    this.update();
}

Cube.prototype.onWindowResize = function() {

    this.camera.aspect = this.width/this.height;
    this.camera.updateProjectionMatrix();
   this.renderer.setSize( this.width, this.height );
     this.render();

 }  

Cube.prototype.render = function() {

    this.renderer.render(this.scene, this.camera);
};

Answer №1

Experiment with using three-onEvent, a tool that allows you to incorporate eventListeners such as click, hover, and gaze.

Here is an example:

geo = new THREE.CubeGeometry(5,5,5);
var mat = new THREE.MeshBasicMaterial({color:0x00aadd});
var mesh = new THREE.Mesh(geo,mat);
mesh.on('click',function(m) {
  m.scale.set(2,2,2); // m represents the mesh
})
myScene.add(mesh);

Alternatively, for hovering:

// hover eventListener 
mesh.on('hover',function(m) {
  // when mouse hovers over the mesh
  m.scale.set(2,2,2); 
},function(m) {
// when mouse moves away from the mesh
  m.scale.set(1,1,1);
});

Lastly, to remove the eventListener:

mesh.off('click');

Answer №2

How to handle resizing in constructor

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

Everything else can be disregarded.

An issue was also found in the onWindowResize function.

Originally written as

Cube.prototype.onWindowResize = function() {

    this.camera.aspect = this.width/this.height;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize(this.width, this.height );
    this.render();   
 }  

The variables this.width and this.height were not properly passed into the function due to a scope error. It seems there was confusion with the terminology.

I should have just stuck with using window.innerWidth & window.innerHeight like in the original code snippet below.

Cube.prototype.onWindowResize = function() {

    this.camera.aspect = window.innerWidth/window.innerHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize( window.innerWidth, window.innerHeight );
    this.render();
 }  

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

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

When attempting to test an ExpressJS API, an error is encountered stating "Cannot read property 'address' of undefined."

After successfully starting the app, I am able to call my API with the following commands: "dev": "env-cmd ./.env nodemon ./src/index.js", "test": "env-cmd ./test.env jest --watch" In server.js: // Loading dependencies const app = express(); ... // Load ...

What is causing the slideshows to suddenly stop functioning?

I've successfully implemented a slideshow in my project, as discussed in my previous inquiry. Although I attempted to add more slideshows using the same code and design, they are not functioning properly. Even the original slideshow has stopped worki ...

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

Preventing duplicate entries in a LocalStorage JSON array by saving data

Recently, I wrote a small script to experiment with localStorage. It's quite basic - you can add items to a JSON array and they will be stored under the key "saved". However, I encountered an issue where duplicate entries were not being prevented in ...

Converting JavaScript table input values to JSON format

I need help saving the value in a table's input as JSON. I tried using serializeArray but it only retrieves 2 data points when I need all 3 (id and value). HTML Code: This is what I have tried: var myRows = { myRows: [] }; var $th = $('table t ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. https://i.sstatic.net/CVs4j.png const d ...

'Sys is not defined' JavaScript error

I've exhausted all my efforts searching for a solution online, but I'm still struggling to find an answer. I am facing a challenge with several projects that were initially developed for .Net 2.0 and hosted on IIS6 Server 2003 32 bit. Now, as pa ...

Simulating nodemailer functionality for testing purposes using Jest

I recently implemented an endpoint for users to reset their passwords. Everything was working smoothly and my tests were passing without any issues until I integrated nodemailer to send password reset emails. For testing, I am using Jest. Oddly enough, w ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

Looping the Connection between Socket.io and Node

I have encountered a problem with my Unity client connecting to my node server using socket.io. While the initial connection is successful and acknowledged, when I try to emit a message to the connected client, the connection seems to get reopened as if a ...

What is the best method for clearing all session cookies in my React application?

Currently, I am working on a project using React. I am trying to find a method to automatically logout the user by deleting all of the session cookies in my React application. However, I have not been able to come up with a solution yet. Is there a way to ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

Utilizing NestJS to pass multiple IDs as parameters in an API

I am working with nestjs for the first time and I've been tasked with creating an API at http://localhost:8000/companies/4/5/8…. Does anyone know how to create this API using the GET(':id') method that can handle multiple parameters? ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Determining in Angular whether a component tag includes a specific attribute

My usage of the app-somecomponent looks like this: <app-somecomponent required></app-somecomponent> I am trying to determine if the app-somecomponent element has the required attribute set in the app-somecomponent.component.ts file without sp ...

The watch function remains inactive until it is triggered by an event

My current issue involves using $watch for pagination on my page. Unfortunately, the data is not appearing until I click on one of the buttons. Below is the relevant code snippet: .controller('AppCtrl', function ($scope, $modal, Faq) { $sco ...

Instructions for deleting a class from the body with jQuery while incorporating AngularJS

When using jQuery $(document).ready(function() { $("#pid1").removeClass("login_page"); }); HTML <body class="login_page" id="pid1" ng-app="myApp" ng-controller="myCtrl"> On the main page, a class is removed, but on the login page I want to ...

Updating the style of a div in ReactJS with instant changes

Currently working on a project where I need to create a self-centering, self-sizing content editable div. The text is centered and the width is already set to 100% of the parent container; my main concern now is the height. I have implemented a function t ...