Skip to content

Instantly share code, notes, and snippets.

@PHAredes
Last active September 11, 2024 17:14
Show Gist options
  • Save PHAredes/b060d316b6c3e9c198328f466d3fb222 to your computer and use it in GitHub Desktop.
Save PHAredes/b060d316b6c3e9c198328f466d3fb222 to your computer and use it in GitHub Desktop.
Usage demo

To run the Three.js demo you described, you'll need to set up a basic web project and include the Three.js library. Here's a step-by-step guide to get you started:

Create a new directory for your project. Inside that directory, create two files:

index.html script.js

To run the demo:

If you have a local web server, start it in the directory containing your index.html and script.js files. If you don't have a local web server, you can use Python to create a simple one. Open a terminal in your project directory and run:

For Python 3: python -m http.server For Python 2: python -m SimpleHTTPServer

Open a web browser and navigate to http://localhost:8000 (or whatever port your local server is using).

You should now see a rotating cube rendered using Three.js. Note: The code uses a CDN to include Three.js. If you prefer to download and include Three.js locally, you can do that instead of using the CDN link.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Demo</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="script.js"></script>
</body>
</html>
const width = window.innerWidth, height = window.innerHeight;
// init
const camera = new THREE.PerspectiveCamera( 70, width / height, 0.01, 10 );
camera.position.z = 1;
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( width, height );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
// animation
function animate( time ) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render( scene, camera );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment