Three.js is a JavaScript library that is built on top of WebGL and is used for rendering animations on the web.
Note: If you are unfamiliar with three.js, please follow this link to read more.
Objects in three.js have properties that allow them to be translated, transformed, and rotated. In this Answer, we'll focus on making an object rotate around its axis.
This can be done using the rotation
attribute of an
rotation
attributeThis attribute is used for rotating an object about its axis. Below is how we invoke it:
shape.rotation.y += 0.01;
shape
is the rotation
is responsible for an object's local rotation, in radians. y
axis and incremented its rotation.Note: Putting this statement inside the rendering function will cause the body to rotate every time the function is called.
set
property with the rotation
attributeThe rotation
attribute also has the set
property that takes a vector as an input and sets rotation accordingly.
Below is the code that renders a cone geometry with a basic material applied to it.
const geometry = new THREE.ConeGeometry (1, 3, 32);const material = new THREE.MeshBasicMaterial({color: 0xEA654});const cone = new THREE.Mesh(geometry, material);
THREE.ConeGeometry
: It creates a cone geometry with the parameters it has been passed.THREE.MeshBasicMaterial
: It creates the required material that we need to apply to our geometry. We also pass the constructor, the color
we want to set.THREE.Mesh
: It takes as parameters, geometry
and material
, and gives us the required shape.We can set the rotation for this cone by using the set
method.
set
property takes as a parameter a 3D vector. Below is how we use set
:sphere.rotation.set(Math.PI/2,0,0)
This rotates the cone by 90 degrees along the x-axis.
The code shown above is of a typical scene in three.js with ConeGeometry
.
rotation
property of our Mesh
object. Note: To read more on how to create a scene, please visit this link.
Free Resources