Three.js Quick Start - Run Spinning-Cube Example
In this post, I am going to run the spinning-cube example for three.js.
https://threejs.org/docs/#manual/en/introduction/Creating-a-scene
What is three.js?
three.js is a JavaScript library to render 3D graphics on a browser.
Example
% mkdir threejs && cd threejs
% mkdir js
% curl -o ./js/three.js https://threejs.org/build/three.js
% tree
.
├── index.html
└── js
└── three.js% vim index.html
% open index.html
index.html (the code is from example)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>My first three.js app</title>
		<style>
			body { margin: 0; }
		</style>
	</head>
	<body>
		<script src="js/three.js"></script>
		<script>
			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.body.appendChild( renderer.domElement );
			const geometry = new THREE.BoxGeometry();
			const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
			const cube = new THREE.Mesh( geometry, material );
			scene.add( cube );
			camera.position.z = 5;
			const animate = function () {
				requestAnimationFrame( animate );
				cube.rotation.x += 0.01;
				cube.rotation.y += 0.01;
				renderer.render( scene, camera );
			};
			animate();
		</script>
	</body>
</html>
You will see the cube is spinning on your browser, as shown on top of this post.
Snippet for what is going on:
- "we need three things: scene, camera and renderer"
- "To create a cube, we need a BoxGeometry"
- we need "render" or "animate loop" to see it
Modify a bit
- Color: blue
- Spin: faster
- Size: bigger -> move the camera closer
% cp index.html modified.html
% vim modified.html
% open modified.html
diff


 
Comments
Post a Comment