Home > Back-end >  why is three.js not rendering this spinning cube? I believe i have everything correct but sometimes
why is three.js not rendering this spinning cube? I believe i have everything correct but sometimes

Time:03-29

I am not getting any errors which is confusing me, it renders a black screen. and because the HTML and CSS snippets are so tiny I believe my fault is hidden somewhere within the JS.

I really haven't worked with three.js much so please don't be too harsh with your criticisms, I know its probably a simple fix but sometimes my brain just doesn't work correctly.

Thanks in advance! :D

// The three.js scene: the 3D world where you put objects
const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  1,
  10000
);



const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xaaaaaa, 1);

document.body.appendChild(renderer.domElement);


const cube = {
  geometry: new THREE.BoxGeometry(1, 1, 1),
  material: new THREE.MeshBasicMaterial({ color: 0x00ff00 })
};

cube.mesh = new THREE.Mesh(cube.geometry, cube.material);

scene.add(cube.mesh);

camera.position.z = 5;

function render() {
  renderer.render(scene, camera);

 
   cube.mesh.rotation.x  = 0.08;
  cube.mesh.rotation.y -= 0.05;
  
  requestAnimationFrame(render);
}
html, body {
    overflow: hidden;
    user-select: none;
  padding: 0;
  margin: 0;
}

canvas {
    width: 100%; 
    height: 100%;
    padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Three.js app</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>
    <script src="script.js"></script>
  </body>
</html>

CodePudding user response:

Start the animation by calling the render function:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  1,
  10000
);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xaaaaaa, 1);

document.body.appendChild(renderer.domElement);

const cube = {
  geometry: new THREE.BoxGeometry(1, 1, 1),
  material: new THREE.MeshBasicMaterial({ color: 0x00ff00 })
};

cube.mesh = new THREE.Mesh(cube.geometry, cube.material);
scene.add(cube.mesh);
camera.position.z = 5;

function render() {
    renderer.render(scene, camera);
    cube.mesh.rotation.x  = 0.08;
    cube.mesh.rotation.y -= 0.05;
    requestAnimationFrame(render);
}
render();                             // <--- 
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/104/three.min.js"></script>

  • Related