Utilize the cube function in JavaScript to zoom in on the cube automatically when the page loads

I have the code below. When the page loads, I would like the cube to zoom out and stop. I am new to 3js and have no idea how to achieve this. I want the cube to start small and then grow into a larger cube before stopping.

 <script>
      //var resultlabel = (document.getElementById('resultvalue').innerHTML);
      //if (resultlabel == 0) {
          var container
          var camera, controls, scene, renderer;
          var objects = [];
          var plane = new THREE.Plane();
          var raycaster = new THREE.Raycaster();
          var mouse = new THREE.Vector2(),
          offset = new THREE.Vector3(),
          intersection = new THREE.Vector3(),
          INTERSECTED, SELECTED;

          init();
          animate();

          function init() {
              container = document.getElementById('canvas1');
              camera = new THREE.PerspectiveCamera(70, container.offsetWidth / container.offsetHeight, 1, 10000);
              //camera.position.z = 2000;
              camera.position.set(3000, 3000, 3000);
              //camera.position.set(1000, 1000, 1000);
              controls = new THREE.TrackballControls(camera, container); //**
              controls.rotateSpeed = 1.0;
              controls.zoomSpeed = 1.2;
              controls.panSpeed = 0.8;
              controls.noZoom = false;
              controls.noPan = false;
              controls.staticMoving = true;
              controls.dynamicDampingFactor = 0.3;

              scene = new THREE.Scene();

              var directionalLight = new THREE.DirectionalLight(0x505050);

              scene.add(directionalLight);
              //var resultlabel = (document.getElementById('resultvalue').innerHTML);
              //if (resultlabel == 0) {

                  var geometry = new THREE.BoxGeometry(500, 500, 500);
                  var ax = ay = az = 0;
                  for (var i = 0; i < 1; i++) {


                      var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ ambient: 0xffffff, map: THREE.ImageUtils.loadTexture('/imgs/12.jpg') }));


                      object.position.x = ax;
                      object.position.y = ay;
                      object.position.z = az;

                      object.scale.x = 2;
                      object.scale.y = 2;
                      object.scale.z = 2;



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

                      light = new THREE.DirectionalLight(0x666699);
                      light.position.set(0, -1, 0);
                      scene.add(light);
                      //back
                      light = new THREE.DirectionalLight(0x666699);
                      light.position.set(1, 0, 0);
                      scene.add(light);
                      // front
                      light = new THREE.DirectionalLight(0x666699);
                      light.position.set(-1, 0, 0);
                      scene.add(light);
                      //right
                      light = new THREE.DirectionalLight(0x666699);
                      light.position.set(0, 0, 1);
                      scene.add(light);
                      //left
                      light = new THREE.DirectionalLight(0x666699);
                      light.position.set(0, 0, -1);
                      scene.add(light);
                      objects.push(object);

                  }


                  var material = new THREE.MeshPhongMaterial({ map: THREE.ImageUtils.loadTexture('/1.png') });
                  var mesh = new THREE.Mesh(geometry, material);

                  scene.add(mesh);

                  renderer = new THREE.WebGLRenderer({ antialias: true });

                  renderer.setClearColor(0xf0f0f0);

                  renderer.setPixelRatio(container.devicePixelRatio);

                  renderer.setSize(container.offsetWidth - 4, container.offsetHeight - 4);

                  renderer.sortObjects = false;



                  renderer.shadowMap.enabled = true;

                  renderer.shadowMap.type = THREE.PCFShadowMap;



                  container.appendChild(renderer.domElement);
                              
                  stats = new Stats();

                  container.appendChild(stats.dom);

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



              function onWindowResize() {

                  camera.aspect = window.innerWidth / window.innerHeight;

                  camera.updateProjectionMatrix();

                  renderer.setSize(window.innerWidth, window.innerHeight);
              }

              function animate() {

                  requestAnimationFrame(animate);

                  render();

                  stats.update();
              }

              function render() {

                  controls.update();

                  renderer.render(scene, camera);
              }
          

Answer №1

For a smooth animation effect, consider using THREE.Vector3.lerp.

To set the destination position for your camera, create a vector3:

var targetPosition = new THREE.Vector3(1500, 1500, 1500);

In your animation loop, include the following:

camera.position = camera.position.lerp(targetPosition, speed);

The 'speed' variable should be a value ranging from 0 to 1, determining the distance the camera will move each iteration.

This technique provides a quick solution, although it has limitations such as never quite reaching the target position. To gain a more in-depth understanding, explore linear interpolation further. Best of luck!

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

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

Establish boundaries for D3.js circle reports

I am currently working on a visualization project where I want to arrange cells with higher values to appear towards the top and left, similar to a gravity force. However, I am facing difficulties in keeping multiple circles within the boundaries of the re ...

Dynamically transferring data from PHP to JavaScript in dynamically generated HTML elements

I have a collection of entities retrieved from a database, each entity containing its own unique GUID. I am showcasing them on a webpage (HTML) by cycling through the entities array and placing each one within a new dynamically generated div element. < ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...

Reveal the class to the global scope in TypeScript

ClassExample.ts: export class ClassExample{ constructor(){} } index.html: <script src="ClassExample.js"></<script> // compiled to es5 <script> var classExample = new ClassExample(); //ClassExample is not defined < ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

Error encountered: Unable to access undefined properties while attempting to make an API call to AirTable using NextJS version 13.4

Currently in the process of learning how to use the App router with NextJS 13.4, I encountered an issue while attempting to make an external API call. Even though I am getting all the data correctly from Airtable, Next throws an error that disrupts my try ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel0 ...

The audio event continues to trigger even after it has been removed using removeEventListener

In my React component, specifically handling an audio track with an HTML <audio> element, I have implemented the following lifecycle methods: componentDidMount() { const {track} = this.props; this.refs.audio.src = track.getTrackUrl(); _.each(t ...

Manipulate the text within a canvas element using JavaScript

In this scenario, suppose json.mes represents the received message from Ajax. There is a button implemented to display the message in a canvas box. Although I have attempted to retrieve the message using getElementById (as shown below), it seems to be in ...

Implementing a NextJS client component within a webpage

I am currently working with NextJS version 14 and I am in the process of creating a landing page. In one of the sections, I need to utilize the useState hook. I have specified my component as "use-client" but I am still encountering an error stating that " ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

Adding a new column to a table that includes a span element within the td element

I am attempting to add a table column to a table row using the code below: var row2 = $("<tr class='header' />").attr("id", "SiteRow"); row2.append($("<td id='FirstRowSite'><span><img id='Plus' s ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

Drop-down selection triggering horizontal auto-scroll

Within my div element, I have a table with dropdowns. The div is set up to be horizontally scrollable. To create the dropdown functionality, I utilized Harvesthq Chosen. Let me provide some context. In Image 1, you'll notice that I've scrolled ...