Using THREE.JS with interactive buttons for initiating and stopping animations

My goal is to trigger an animation from the GUI using THREE.js.

The interface consists of two buttons, "Start" and "Reset," meant to control the rotation of a sphere. Clicking on the "Start" button should launch the animation, changing the button text to "Pause." Subsequent clicks will pause or resume the animation.

I am facing a challenge in managing the rendering of the animation alongside these user interactions and the render() function in THREE.JS.

This is what I have accomplished so far:

// Setting boolean values for animation initiation and running
var initAnim = true;
var runAnim = false;

// Retrieving startButton and resetButton elements
var startButton = document.getElementById('startElementId');
var resetButton = document.getElementById('resetElementId');

// Function for Start Button
startButton.onclick = function StartAnimation() {
  if (initAnim) {
    initAnim = false;
    runAnim = true;
    theta = 0;
  }
  
  // Handling Start and Pause functionality
  if (runAnim) {
    startButton.innerHTML = 'Pause';
    runAnim = false;
    render();
  } else {
    startButton.innerHTML = 'Restart';
    runAnim = true;
  }
}

// Function for Reset Button
resetButton.onclick = function ResetParameters() {

  // Resetting StartButton to original state
  startButton.innerHTML = 'Start';

  // Stopping the animation
  initAnim = true;
  runAnim = false;
}

For the rendering logic in my render() function:

function render() {

  // Incrementing timer 
  timer += clock.getDelta()*0.1;
  theta = -timer;

  // Triggering rendering function
  requestAnimationFrame(render);

  // Implementing camera rotation
  rotateCamera();

  controls.update();

  // Rendering the scene
  renderer.render(scene, camera);
}

My attempt involves invoking the render() function upon clicking the startButton to initiate the animation. However, I struggle with transitioning from a stationary sphere to one that rotates after the initial click.

If anyone has insights on resolving this issue, I would greatly appreciate it.

Thank you in advance.

Answer №1

To pause, simply add a return statement before the requestAnimationFrame in the render function:

function render() {
  if (!isPlay) return;

  //...

  // Call rendering function
  requestAnimationFrame(render);

  //...
}

[ https://jsfiddle.net/yr9ogsh8/ ]

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

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

Limiting the space character in a password field with regular expressions in JavaScript

Currently, I am facing the challenge of implementing a RegEx expression on a property within a model on an MVC website that I am currently developing. While I understand the individual components of the expression, I am struggling to combine them effectiv ...

<h1> </h1> Using attributes in a JavaScript function

Hello, I am trying to figure out how to inherit the h1 style CSS inside a JavaScript function called myFunction. Currently, when the button is clicked, it just displays the default h1 style. Any help would be appreciated. Thank you! <html> <st ...

Is there a way to send an AJAX request to an MVC action from a JavaScript file?

In a file named job.js, there is code that works perfectly when run on localhost but results in a 404 error when run on an intranet server with an application name. Job.updateJob = function () { $.post('/Builder/ListJobItems', function (dat ...

Tips for invoking a JavaScript function script through PHP

<?php echo "<script type='text/javascript'>error_warning('Error!'); </script>"; ?> <!DOCTYPE html> <html stuff> <div id="alert_box" class="alert"></div> < ...

Is there a way in javascript, jquery, and plupload to dynamically pass a parameter to the URL without needing to reload the page or object?

I've recently taken over a project that utilizes plupload. I am encountering an issue where I need to change the URL of the object after it has been loaded. However, I'm unsure if this is possible and what steps I would need to take to achieve th ...

Step-by-step guide on crafting a scrolling marquee with CSS or Javascript

I am in need of creating two marquees for a website project. The first marquee should showcase a repeating image while the second one should display links, both spanning the browser window at any size. It is crucial that the marquee items are displayed fro ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...

Best practice for filling an array using a promise

I am completely new to the world of modern JavaScript. My goal is to fill an array with data that I receive from a promise in a helperService. export class PeopleTableComponent implements OnInit { people: Array < Person > = []; constructor( ...

What steps can be taken to ensure a dropdown selection is required when a specific variable is true?

How can I create an AngularJS dropdown that requires a selection only when a specific variable, such as 'x', is set to true? If 'x' is false, it should allow saving without a selection. Below is the code for my dropdown: <select cla ...

Updating a webpage's background image using Jquery and PHP every 10 seconds

I am in the process of designing a webpage for my hobby radio station. Currently, I have the artist and title displayed, but I would like to take it a step further and have the background change based on the artist playing. For example, when Phil Collins i ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Is the Angular-fullstack generator production application experiencing issues with serving socket.io correctly?

Having a bit of trouble with two angular-fullstack apps deployed on AWS using the same setup and configuration. It appears that socket.io-client/socket.io.js is not being properly served on one of them, despite both apps having identical settings. There ...

The firebaseui.js code encountered an error because it was unable to read the property 'call' as it was undefined

Currently, I am facing an issue while trying to implement Firebase ui auth in my app by referring to Google's Github documentation. While the email sign-in functionality is working smoothly, I am encountering problems with the phone sign-in option. ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Creating a dynamic nested form in AngularJS by binding data to a model

Creating a nested form from a JSON object called formObject, I bind the values within the object itself. By recursively parsing the values, I extract the actual data, referred to as dataObject, upon submission. To view the dataObject in a linear format, r ...

Stop Scrolling in VueJS

I am currently facing a challenge in preventing scrolling only when the lightbox component is open. I prefer not to rely on any external libraries or plugins for this task. Within my App.vue file, I have included the "LightBox" component. Therefore, it se ...

How to smoothly scroll a child div when the parent div is set as position sticky in vue JS

My landing page requires a unique feature: when a user enters a specific <section>, that section should become fixed while the elements inside the corresponding <div> start scrolling. Once the inner div has finished scrolling, the parent <se ...