Hello, three.js community! I need some help.
I am a beginner and am trying to make a basic cube that you could rotate using the orbit controls. I looked at different examples of this exact same project, but I have no idea what I might be missing. When I console.log the scene’s children elements, the cube is included in the children. However, in the viewport, the canvas is there, but not the cube.
Here is what the viewport looks like: (The gray rectangle is the canvas)
Below is my code:
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css">
<title>Vite App</title>
</head>
<body>
<script type="module" src="/main.js"></script>
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
</body>
</html>
main.js:
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth/2, window.innerHeight/2);
document.body.appendChild(renderer.domElement)
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf5f5f5);
const fov = 75;
const aspect = window.innerwidth/window.innerHeight;
const near = 0.1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(5, -5, 10)
const controls = new OrbitControls( camera, renderer.domElement );
controls.enable = true;
controls.enableRotate = true;
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
controls.minDistance = 100;
controls.maxDistance = 500;
controls.maxPolarAngle = Math.PI / 2;
controls.update();
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshPhongMaterial({color: 0x44aa88});
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 0, 0);
scene.add(cube)
camera.lookAt(cube.position)
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(0, 2, 10);
scene.add(light);
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
renderer.render(scene, camera);
animate();
If you have any suggestions as to why the cube might not be appearing, please let me know.
Thank you!