Recently, I encountered an interesting issue with some code I found on a tutorial website. The code worked perfectly when I used the variable 'canvas', but when I changed it to something else like 'canvas2', it caused unexpected behavior. I'm curious to understand why this change led to problems.
<html>
<script type = "module">
import * as THREE from "../three.js/build/three.module.js"
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
renderer.render(scene, camera);
}
main();
</script>
<body>
<canvas id="c" width="1200" height="600" >
</canvas>
</body>
<script>
</script>
</html>
Curiously, when I attempt to alter the canvas-related lines as shown below, the code no longer functions as intended:
const somethingElse = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({somethingElse});