create a web page that displays an animated rotating 3d cube in javascript

To create an animated, rotating 3D cube in JavaScript, we can use the Three.js library. Here's an example:

  1. First, we need to include the Three.js library in our HTML file. We can do this by including the following script tag:
index.tsx
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
90 chars
2 lines
  1. Next, we'll create a div in our HTML file where the cube will be displayed:
index.tsx
<div id="cubeContainer"></div>
31 chars
2 lines
  1. In our JavaScript file, we'll create a scene, a camera, a renderer, and a cube object:
index.tsx
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("cubeContainer").appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
501 chars
16 lines
  1. We can then set the cube to rotate by adding the following code to our render loop:
index.tsx
function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();
156 chars
8 lines
  1. Finally, we'll style our container div with CSS to make the cube appear in the center of the page:
index.tsx
#cubeContainer {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
119 chars
8 lines

That's it! With these steps, we've created an animated, rotating 3D cube in JavaScript using the Three.js library.

gistlibby LogSnag