Three.js is a popular JavaScript library for creating 3D graphics in web browsers. Here’s a brief tutorial on getting started with Three.js. At the end you find a linked repository with the code.
Before you can use three.js, you need somewhere to display it. Save the following HTML to a file on your computer, along with a copy of three.js in the js/ directory, and open it in your browser.
<!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>
// Our Javascript will go here.
</script>
</body>
</html>
In your JavaScript file, create a new Three.js scene and add a camera and a renderer:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer({canvas: document.getElementById("myCanvas")});
To create a 3D object in Three.js, you’ll need to define its geometry and its material. For example, to create a green cube:
var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
To animate the scene, you’ll need to use the requestAnimationFrame function and update the position of the objects in the scene. For example, to rotate the cube:
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
To animate the scene, you’ll need to use the requestAnimationFrame function and update the position of the objects in the scene. For example, to rotate the cube:
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
Textures can be used to add images or patterns to the surfaces of the 3D objects. To create a texture, first, load the image file into the scene using the TextureLoader()
method and create a material using the texture as its map. You can choose any picture for the texture.
var texture = new THREE.TextureLoader().load( 'texture.jpg' );
var material = new THREE.MeshBasicMaterial( { map: texture } );
Three.js is a nice JavaScript library for creating 3D graphics in web browsers. You can start with this simple tutorial to animate a cube in the browser. You find additional material in the documentation on their website. I also created a little project on github with the code and the right structure for you. The README.md shows you, how to run this in VSCode. You also find a slightly different version on Codepen. Feel free to use it as you like. I hope this helps you getting started with three.js.