Clicking to rotate causes the model to disappear in OrbitControls.js

I have incorporated OrbitControls.js into my website to enable users to zoom in/out and rotate 3D models. However, I am encountering an issue where clicking anywhere on the page causes the model to disappear and disables the model switching buttons. Previously, zooming in/out was functional, but rotating was not.

Any assistance would be greatly appreciated.

HTML

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <title>Visualising Cells</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <script src="three.js"></script>
    <script src="ColladaLoader.js"></script>
</head>
<body>
    <script src="OrbitControls.js"></script>
    <script src="main.js"></script>

    <div class="float-btn">
        <button type="button" id="LBC">Load Red Blood Cell</button>
        <button type="button" id="LEC">Load Egg Cell</button>
    </div>

    <div class="float-txt">
        <div style="color:#000000">
          <div style="font-family: Arial">
            <div style="font-size: 18px">
                 <div style="text-decoration: underline">
                     <h1>Visualising Microscopic Cells</h1>
                </div>

             <div class="instructions">
                 <div style="color:#000000">
                     <div style="font-family: Arial">
                         <div style="font-size: 16px">
                            <div style="text-decoration: underline">
                                 <h2>Instructions</h2>
                             </div>

             <div class="instruction-txt">
                <div style="color:#000000">
                    <div style="font-family: Arial">
                        <div style="font-size: 14px">
                            <p><u>Zoom In:</u> <strong>Up Arrow</strong> <br><u>Zoom Out:</u> <strong>Down Arrow</strong></br></p>
                        </div>

             <div class="Model-Location" id="target">
            </div>
</body>
</html>

.js

var myModel; // used to reference the most recently-loaded model

$(document).ready(function() {
    // when the page has loaded, add click functions to the two buttons
    $("#LBC").click(function() {
        toggleModel("blood");
    });

    $("#LEC").click(function() {
        toggleModel("egg2");
    });
});

function toggleModel(modelName) {
    // remove the existing model from the scene
    scene.remove(myModel);
    // add the chosen model
    loadModel(modelName);
}

function loadModel(modelName) {
    // add the specified model
    loader.load(modelName+'.DAE', function (collada) {
        myModel = collada.scene;
        myModel.position.x = 0;
        myModel.position.y = 0;
        myModel.position.z = 0;
        myModel.updateMatrix();
        scene.add(myModel);                
    });
}

var width = window.innerWidth;
var height = window.innerHeight;

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.01, 500 );
camera.position.z = 0.16;
camera.position.x = 0;
camera.position.y = 0;
scene.add(camera);

var controls = new THREE.OrbitControls( camera );

var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height); 
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
renderer.setClearColor("rgb(181,181,181)");

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

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

var loader = new THREE.ColladaLoader();

// load the default model
loadModel("egg2");

document.addEventListener('keydown', function(event) {        
    console.log(camera.position.z);
    if (event.keyCode == 38) {
        // don't scroll the window        
        console.log("Up Arrow Pressed");
        event.preventDefault();
        if (camera.position.z >= 0.1) {
            camera.position.z = camera.position.z - 0.01;
        }

    }
    else if (event.keyCode == 40) {
        // don't scroll the window
        event.preventDefault();
        console.log("Down Arrow Pressed")

        if (camera.position.z < 0.2) {
            camera.position.z = camera.position.z + 0.01;
        }

    }
}, true);

render = function () {
    requestAnimationFrame(render);

    // object.rotation.x += 0.0;
    // object.rotation.y += 0.0;

    renderer.render(scene, camera);            
    // controls.update();
};

controls.addEventListener('change', render );

render();

Answer №1

After making some adjustments to your fiddle, I managed to get it up and running. Due to the absence of your collada models, I utilized two models from the three.js examples directory instead.

The issue you were experiencing was quite peculiar...

Take a look at the non-functional scene here: https://jsfiddle.net/wilt/0c4mfo85/3/

Now, compare it to the working scene: https://jsfiddle.net/wilt/0c4mfo85/4/

The main distinction between the functioning scene and the malfunctioning scene lies in the css rule. I eliminated position: fixed from the style of your canvas. I'm uncertain as to why this simple change had an impact...

canvas {
    position: fixed;
}

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 transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

How to emphasize a dataset in ChartJS stacked bar chart by hovering over the legend?

My Chart.js displays a horizontal stacked bar chart with legends corresponding to different classes. Here's a snippet (using dummy data, please ignore the random names): https://i.sstatic.net/XNTZZ.png The left labels represent users, while the legen ...

How can you send Django context data to a JavaScript variable?

I need to send each value of the {{ i.nsn }} to the ajax script one by one. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} Instead of repeating the ajax script, I want it to function with a single click. <script> var nsn = " ...

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...

The data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...

Sending JSON data from PHP to JavaScript using Ajax

Currently, I am attempting to transfer a JSON object from a PHP script to a JavaScript file using Ajax. The code I have been using successfully for a single string is now being modified to accommodate multiple strings within a JSON object. Below are snippe ...

Using a comma as a parameter separator is not valid

Having trouble setting up a WhatsApp button with a custom message, I wrote a JavaScript script and called it using onclick. I've tried adjusting quotation marks but nothing seems to be working. This issue might seem minor, but as a beginner in coding ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

The callbacks from using Mongoose findById() only yield results for irrelevant information

I am currently using Mongoose for database operations. I am experiencing an issue where the findById() method is sometimes returning results, but not consistently: Case 1: Invalid Query models.Repo.findById("somefakeid", function(err, result){console.log ...

Error thrown: SyntaxError - Forbidden break statement in AJAX code execution

Trying to exit a loop nested within a statement has been a challenge. Despite researching similar questions on stackoverflow, I have not found a solution that works. Below is the current code in question: for (var i = 0; (i < 10); i++) { ...

Navigating React Redux Pages Using React Router

At the moment, I am exploring the possibility of creating an application using React and Redux. Most examples I've come across make use of React Router, so I'm curious about its purpose. My application will consist of multiple pages (at least 20 ...

When making an Axios API request in Next.js, an error is encountered stating that the property 'map' cannot be read as it is undefined

Hey there! I've been trying to fetch data from the API endpoint in my NextJs application using axios. However, whenever I try to map over the retrieved data, NextJs keeps throwing the error message "TypeError: Cannot read property 'map' of ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

What might be causing the in-viewport javascript to not work in my code?

Why is my in-viewport JavaScript code not functioning properly? Link to JSFiddle code When the Click to move button is clicked, the cat image will slide correctly. However, when implementing the following code: if($("#testtest").is(":in-viewport")) ...

Getting JSON or JSONP data through a XAMPP local server is a straightforward process

After setting up a local server with XAMPP, my goal is to retrieve JSON / JSONP data from that server. Additional query: Do I need to upload the JSON file directly onto the server? Or can I achieve this using somePHPcoding? If so, which? I have come ac ...

"Encountering a problem with using setState in React Hook useEffect

I am currently utilizing the useState hook with two arrays: imageList and videoList. In my useEffect hook, I iterate through the data using forEach method. If the type of the item is an image, it should be pushed to the imageList array. However, after exec ...