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.