Vue Application experiences issues resizing Three.js Animation in Canvas

Currently, I am deep diving into learning Three.js within a Vue.js component. Take a look at my code snippet:

<script>
import * as THREE from "three";

export default {
  name: "Scene",
  mounted() {
    this.initializeThree();
  },
  methods: {
    initializeThree() {
      this.canvas = document.getElementById("background");

      this.scene = new THREE.Scene();
      this.camera = new THREE.PerspectiveCamera(75, 2, 0.1, 1000);

      this.renderer = new THREE.WebGLRenderer({
        canvas: this.canvas,
        alpha: true,
        antialias: true,
      });
      this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);

      let geometry = new THREE.BoxGeometry(1, 1, 1);

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

      this.camera.position.z = 2;

      this.cubes = [
        this.createInstance(geometry, 0x44aa88, 0),
        this.createInstance(geometry, 0x8844aa, -2),
        this.createInstance(geometry, 0xaa8844, 2),
      ];

      this.animate();
    },

    animate() {
      this.cubes.forEach((cube) => {
        cube.rotation.y += 0.01;
      });
      this.adjustCanvasSize();
      this.renderer.render(this.scene, this.camera);
      requestAnimationFrame(this.animate);
    },

    adjustCanvasSize() {
      const canvas = this.renderer.domElement;
      // find out the current display size of the canvas
      const width = canvas.clientWidth;
      const height = canvas.clientHeight;

      if (canvas.width !== width || canvas.height !== height) {
        this.renderer.setSize(width, height, false);
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
      }
    },

    createInstance(geometry, color, x) {
      const material = new THREE.MeshPhongMaterial({ color });

      const cube = new THREE.Mesh(geometry, material);
      this.scene.add(cube);

      cube.position.x = x;

      return cube;
    },
  },
};
</script>

<style scoped>
canvas {
  display: block;
  width: 100%;
}
</style>

If I resize the window to a smaller size than the initial size when the page loaded, it works perfectly in Chrome developer tools where the canvas width and height adapt accordingly. However, if I increase the size beyond the initial dimensions, it remains unchanged and does not scale. This resizing behavior seems isolated only to the developer tools and not reflected on the actual webpage.

Answer №1

Your resize function logic needs some adjustment. Currently, you are retrieving the current width using:

const width = canvas.clientWidth;
and then simply assigning it back to the same variable. This is similar to:

width = canvas.width;
canvas.width = width;

To improve this, follow the standard method used in Three.js examples. Instead of checking for resizing on every animate() frame, set an event listener for window resizes and adjust the canvas dimensions accordingly based on the window size:

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

function onWindowResize() {
    renderer.setSize(window.innerWidth, window.innerHeight);

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
}

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

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

Trouble with Google Bar Chart's Background Color not Updating

I'm having issues with the background color in my google Material Charts static api library. Despite entering a specific color code, the change is not being reflected when the page loads. These are the options I have set: var options = { b ...

Struggling to integrate Bloompass and EffectComposer in Three.js

I'm struggling to incorporate post-processing using EffectComposer and BloomPass Even after reviewing previous stack overflow posts and ensuring that I have a renderpass, bloompass, copyshader with rendertoscreen set to true on the last pass, it stil ...

Is it necessary to include Babel when integrating Webpack?

After reading an informative article, it is highlighted that Babel’s plugin-syntax-dynamic-import plays a crucial role in enabling lazy loading. Without this, the syntax const AppHome= () => import("@/components/AppHome"); will not be compiled by webp ...

Adjusting the styling of a webpage in real-time

Here is the CSS code I am working with: .myTabs .JustForFun .ajax__tab_inner:hover { width: 109px; background: url ("/images/csc_tr.png") no-repeat 100% 0%; margin-right: 2px; background-color: #BBC614; } I want to change the background-c ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

The model I loaded seems to be completely black, and I'm unsure how to troubleshoot the issue with the applied texture material

I'm encountering an issue where my model is not being rendered by three.js. I have employed the JSONLoader to load the model, utilized ImageUtils.loadTexture for the texture, and created a MeshPhongMaterial. However, despite the basic code functioning ...

The data returned by AJAX is not in the correct order in the database

function retrieveData() { <?php $stmt = $conn->prepare("SELECT id, name FROM data"); $stmt->execute(); $stmt->bind_result($id ,$name); while ($stmt->fetch()) {?> processData (<?php echo "'$id'";?>,<?php echo "&apo ...

Tips for updating the minimum value to the current page when the button is pressed on the input range

When I press the next button on the current page, I want to update the value in a certain way. https://i.stack.imgur.com/XEiMa.jpg I have written the following code but it is not working as expected: el.delegate(".nextbtn", "click", f ...

Guide to Implementing the GitHub Fetch API Polyfill

I'm facing an issue with making my code compatible with Safari by using the GitHub Fetch Polyfill for fetch(). I followed the documentation and installed it using: $ npm install whatwg-fetch --save Although I completed this step, I am unsure of how ...

After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this: <script type="text/javascript> var rootpath = ""; $(document).ready(function () { rootpath = "@VirtualPathUtility.ToAbsolute("~/ ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...

Problem with Submitting Form using Search Bar

I've tried everything, but I can't seem to get this search form to submit. <div id="search_bar_container" style="z-index:99999"> <div class="container"> <form action="tour-list-search-results.php" method="post" name="searc ...

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

What is the best way to format a date input field so that when a user enters a year (yyyy), a hyphen (-

Need help with date formatting in the format yyyy-mm-dd. Seeking a way to prompt user input for the year and automatically append "-" to the date as needed. Also utilizing a datepicker tool for selecting dates. ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

Error occurred while executing 'npm start' command in ReactJS due to the module 'babel-code-frame' being unable to be located

Every time I attempt to run 'npm start' in the frontend of my application, the terminal spits out a massive error. My package.json file doesn't show any script errors, and I've deleted the 'node_modules' folder and reinstalle ...

Transform UNIX timestamp into a date with the power of VueJS

Currently, I am utilizing query builder in AEM with Cloud Service to extract the jcr:created date of pages via a Servlet. To access this servlet, I have integrated Vue JS into my workflow. The issue I am facing is that the date returned by the servlet is ...