Subscribe to our free newsletter

To make sure you won't miss any valuable content we share with our community.

Texture of A Dice: Cube Texture example

We have provided a lot of tutorials about the textures on our blog. Some of which, we have directly worked on the textures, and others that we have used the texture in our three.js examples. However, in none of these examples we have had multi-texture objects, or in other words, we have never faced a situation in which we had to place different textures for the different sides or part of it. In this tutorial, we will work on an example that covers this situation. This example includes designing a dice or a cube with different textures on each of the sides. To make this happen, we should first download the image of each of the faces and then map them in the materials onto the object. As always, we begin with the basics and get started from creating the Vite plugin, to have all all the necessary files inside our project folder and then will add the script related creating and animating a dice. The project can be used when you want to style your website in a beautiful way at the time the user is waiting for some process to get completed.

Getting started with the basics:

We are going to get started with the simple elements of a Three js scene including the camera, the renderer, the scene, the object and the light source (if necessary). Before we do that, we’d rather use the Vite plugin to be able to easily create all the folders and file that you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir DiceTexture
cd DiceTexture
Then, inside of the your project folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then enter the name of the project. You can write the name of your project as the name. And also the package (the name is arbitrary and you can choose anything that you want). Then select vanilla as the framework and variant. After that, enter the following commands in the terminal: cd DiceTexture
npm install
npm install three Afterward, you can enter the javascript code that you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as a sphere. Also do not forget to install the Three.js package library every time create a project:

The code:

Now, enter the following script in the main.js file:

import * as THREE from '/node_modules/three/build/three.module.js'
import { Mesh } from 'three'
var camera, scene, renderer, dice, cube;
init();
animate();
function init() {
     renderer = new THREE.WebGLRenderer();
     renderer.setSize(window.innerWidth, window.innerHeight);
     document.body.appendChild(renderer.domElement);
     scene = new THREE.Scene();
     camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
     camera.position.set(110, 110, 250);
     camera.lookAt(scene.position);
     scene.add(camera);
     var materials = [
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/1.jpg')
          }),
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/2.jpg')
          }),
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/3.jpg')
          }),
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/4.jpg')
          });
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/5.jpg')
          }),
          new THREE.MeshStandardMaterial({
          color: 0xffffff,
          map: new THREE.TextureLoader().load('./img/6.jpg')
          })
     ];
     cube = new THREE.BoxGeometry(40, 40, 40);
     dice = new THREE.Mesh(cube, materials ); 
     scene.add(dice);
     const width = 20;
     const height = 20;
     const intensity = 2500;
     const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
     rectLight.position.set( 250, 250, 250 );
     rectLight.lookAt(scene.position );
     scene.add( rectLight )
}
function animate() {
     requestAnimationFrame(animate);
     dice.rotation.x += .05;
     dice.rotation.y += .05;
     dice.rotation.z += .05;
     renderer.render(scene, camera);
}


Now if we save the code, and enter the following command in the terminal: npm run dev We should see the following result:

Which is a rotating dice with a beautiful animation on all three axes.

Explaining the code:

In the above code, we set the camera, scene, and renderer. Then, we defined the material of all the sides of the dice. The materials, load the texture related to any of the sides. You can enter any photo with any design in the directory of the images. Afterward, we created a cube using the BoxGeometry() function and added the material to it. Notice that all of these codes up to here are written inside the init() function. We wrote another function for the animation. And in the end, we executed the 2 functions.

Conclusion

In this article, we have managed to create a dice with a certain kind of animation in Three.js. This example required a certain kind of applying texture. Meaning that we had to add different textures for different sides of the cube or the dice. To do so, we added these texture images to six materials concerning the six sides of the cube. The example we worked on in this article was very simple but at the same time was the question of many of those who had learned how to use different kinds of textures but did not know how to apply different textures on different sides of the same cube.

Download this Article in PDF format

3d websites

Arashtad Custom Services

In Arashtad, we have gathered a professional team of developers who are working in fields such as 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications as well as blockchain development.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Fill in the Form
Blockchain Development

How to Add Background Using Orbit Controls in Three JS

One of the most exciting projects is adding a background scene in Three js. The scene could be retrieved from an HDRI image that has been captured in 360 degrees from a scene like the interior space of your room or an open ambient like a garden, jungle, or mountain. You can create any of these images yourself but that is not the subject of this tutorial. Instead, we are going to get one of these images from a website and using the orbit controls, give the user the capability of turning around the object and seeing everything in 360 degrees. We can also add objects to the scene and give them color or increase their metalness and decrease their roughness to become a sphere-shaped mirror.

Adding Background in Three JS

The possibilities are infinite and there is a lot of what you can do. For instance, you create an interior design of an empty room by adding 3d models of different furniture, carpets, rugs, and so on. This tutorial is the beginning of the creation of your favorite virtual world. You can make your dream home virtually and watch it from all different aspects. And as we have said in other Three js tutorials, once you start working with Three js, the sky is the limit.

The Essentials You Need to Know Before Applying Three JS Background

We are going to get started with the simple elements of a Three js scene including the camera, the renderer, the scene, the object, and the light source (if necessary). Before we do that, we’d rather use the Vite plugin to be able to easily create all the folders and files that you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir BackgroundScene
cd BackgroundScene
Then, inside the glowing sphere folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then, enter the name of the project. You can write glowingSphere as the name. However, the name is arbitrary and you can choose anything that you want. Then, select vanilla as the framework and variant. After that, enter the following commands in the terminal: cd BackgroundScene
npm install
Afterward, you can enter the javascript code that you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as an sphere. Besides, do not forget to install Three js package library every time you create a project: npm install three Now, enter the following script in the main.js file

import * as THREE from 'three';
import { Mesh } from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight , 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
     antialias : true
})
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
//creating a sphere
const geometry = new THREE.SphereGeometry(5, 50, 50);
const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})
const sphere = new THREE.Mesh(geometry,material);
scene.add(sphere);
camera.position.z = 15;
function animate(){
     requestAnimationFrame(animate);
     renderer.render(scene,camera);
     sphere.rotation.y += 0.003;
}
animate();

The above code can be used as a boilerplate for later projects. The output of this code will be blue sphere like the following photo. But, to be able to show that, you should write the following command in the terminal: pm run dev

Setting Up Background Using Orbit Controls in Three JS

Now, we want to create a background scene to be added, but before we do that, we need to change the rendering from animation to orbit controls so that instead of the rotation of the object, we can have control over changing the scene from the camera point of view. Doing as such gives us the capability to see the HDRI image from all angles. First off, we need to import the 2 following libraries:

import {OrbitControls} from "/node_modules/three/examples/jsm/controls/OrbitControls.js";
import Stats from "/node_modules/three/examples/jsm/libs/stats.module.js";


Then, what we will do is to change the rendering scripts at the end from:

function animate(){
     requestAnimationFrame(animate);
     renderer.render(scene,camera);
     sphere.rotation.y += 0.003;
}
Animate();


To:

const controls = new OrbitControls(camera, renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
      render();
}
const stats = Stats();
document.body.appendChild(stats.dom);
function animate() {
      requestAnimationFrame(animate);
      render();
      stats.update();
}
function render() {
      renderer.render(scene, camera);
}
animate();


Now we should be able to orbit around the object. The next thing we should do is to change the material from basic to standard and create the mirror effect:

const geometry = new THREE.SphereGeometry();
const material = new THREE.MeshStandardMaterial({
      color: 0xffffff,
})
material.roughness = 0;
material.metalness = 1;
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);


Finishing the Background Project

Finally, we get to the most exciting part and that is adding the HDRI image to the background. To do this, we need to first find one of these images from a website like https://polyhaven.com/. Afterward, we should create a folder called images and paste the HDRI image into it. In the end, add the following scripts to be able to render the background in the scene:

import {RGBELoader} from "/node_modules/three/examples/jsm/loaders/RGBELoader.js";
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 0.6;
renderer.outputEncoding = THREE.sRGBEncoding;
new RGBELoader().load("/images/solitude_4k.hdr", function(texture){
      texture.mapping = THREE.EquirectangularReflectionMapping;
      scene.background = texture;
      scene.environment = texture;
})


Now, if we save the script, the result will be:

And as you left-click on the page and take it to left, right, above, or below, you will see that you can see the scene from all the different angles. Also, as we have defined the metalness of the material of the sphere to one and the roughness to 0, we can see the mirror effect on the sphere, reflecting the background scene in a realistic way. Somehow, we can say that we do not need any light sources but notice that if your object is near the ground or in any other situation where you need to see the shadow of the ball, you will have to add a light source to the scene and place it in a way that the rays of the source have the same direction as of the sun.

Wrapping Up

In this tutorial, we have managed to add the background to the scene. To do this, we first started with the Vite plugin and a boilerplate code that we have used in most of our Three js projects. Then, we removed the rotation animation and instead of that, we added the orbit controls for the users to be able to see any angle of the scene they want using their cursor. The next thing that we did was to change the material of the object from basic to standard so that we could then add the mirror effect to the surface of the sphere.

To make this happen, we set the metalness to 1 and the roughness to 0. After that, we looked for an HDRI image and added it to our directory. Eventually, we wrote the scripts related to adding the background scene and the result was astonishing! Of course, you can do the same process for the interior design of a room and add some realistic furniture and other elements to the background scene which is the room and create your own version of virtual reality.

Download this Article in PDF format

metaverse

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
Blockchain Development

Making A Three JS Cube: A Useful Guide

One of the simplest projects that will help you learn the basics of Three js, is designing a cube, changing the color, light sources, materials, adding textures, and so on. Of course, if you want to just get started with Three js, this example is one of the most idealistic projects that you need in order to learn it. Fewer tutorials will teach you everything about manipulating the simple cube and how you can decorate it in the very first tutorial. But, here we have provided the step-by-step guidelines for getting started with the process.

The things that you will learn throughout this tutorial are creating a Three js using Vite plugin, creating a cube with basic mesh material and also standard mesh material. Afterwards, we will add point light in order to be able to see the cube created with the standard mesh material. The next thing that we will try will be to create a wireframe for the cube. Finally, we will add a texture to the cube to make it look nice and beautiful.

The Basics of Making A Three JS Cube

We are going to get started with the simple elements of a Three js scene including the camera, the renderer, the scene, the object and the light source (if necessary). Before we do that, we’d rather use the Vite plugin to be able to easily create all the folders and file that you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir cube
cd cube
Then, inside of the glowing sphere folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then, enter the name of the project. You can write glowingSphere as the name. Also, the package name is arbitrary and you can choose anything that you want. Then, select vanilla as the framework and variant. After that, enter the following commands in the terminal: cd cube
npm install
Afterward, you can enter the javascript code that you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as an sphere. Also do not forget to install Three js package library every time create a project: npm install three Afterward, you can enter the following script in the main.js file:

import * as THREE from 'three';
import { Mesh } from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight , 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
     antialias : true
})
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
//creating a sphere
const geometry = new THREE.SphereGeometry(5, 50, 50);
const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})
const sphere = new THREE.Mesh(geometry,material);
scene.add(sphere);
camera.position.z = 15;
function animate(){
     requestAnimationFrame(animate);
     renderer.render(scene,camera);
     sphere.rotation.y += 0.003;
}
animate();


The above code can be used as a boilerplate for later projects. The output of this code will be blue sphere like the below photo. But to be able to show that, you should write the following command in the terminal: npm run dev

If you want to change the sphere to cube change the following script from:

const geometry = new THREE.SphereGeometry(5, 50, 50);


To:

const geometry = new THREE.BoxGeometry(4, 4, 4);


If you save the code, the result will be a rotating cube like this:

And if you want to change the material from basic mesh to standard, change the code from:

const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})


To:

const geometry = new THREE.BoxGeometry(4, 4, 4);
const material = new THREE.MeshStandardMaterial();
material.color = new THREE.Color(0x3268F8);
material.roughness = 0.2;
material.metalness = 0.7;


Besides, add 2 point lights to the scene so that you can see the cube made with the standard mesh material. To do so, enter the below script twice with 2 different names:

const pointLight = new THREE.PointLight(0xffffff, 0.1);
pointLight.position.x = 2;
pointLight.position.y = 3;
pointLight.position.z = 4;
pointLight.intensity = 2;
scene.add(pointLight);


Result:

If you want to turn the cube to a wireframe, you can set the wireframe property as true. Then, for adding texture, set it to false:

material.wireframe = true;


Save the script and the result will be:

Adding Texture to the Cube in Three JS

One of the important things that makes your objects more beautiful and decorated, is adding texture to them. The process is so easy, you can google any texture that you want and download it. Then use the map property of the material and load the photo of the texture of the surface of the object by giving the address of the image. For instance, we want a Polka dot texture on our cube. We google it and find this photo:

Now, we will create a new folder called img in the directory of the project. And, we add the above texture image to that folder. Then, we will add the below code under the material and save the main.js.

material.map = new ;
THREE.TextureLoader().load('./img/polkadot.jpg');


The result will be exciting:

You can add any other texture of your choice and taste to the surface of the cube. Notice that some textures need precision in the placement. For instance, if you want to design a dice, you will need to map any of the numbers to a certain side of the cube. And some tricks will be needed to have accurate mapping. Doing this task is not the subject of this article, but we will hopefully cover it in our future tutorials.

Final Decision

In this tutorial, we managed to create a Three js project from scratch and started with a boilerplate code. Then, we added a cube instead of a sphere to the scene. Afterward, we changed the material from basic to standard, and to be able to see that, we added 2 point lights with high intensities. The next thing that we did was to create the wireframe of the cube and set it to true.

After that, we set it to false again, in order to add some textures to the cube. The most interesting part of the tutorial was when we added the texture. To do so, we first googled the texture of our choice which was a polka dot in our case and added it to a folder inside the directory of the project, and finally added the map property to the material to see the texture on the cube.

Download this Article in PDF format

metaverse

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Fill in the Form
3D Development