Adding Textures in ThreeJs
Today we’ll look how to apply texture for a geometry. Here I’m going to use this texture which looks like wood. https://www.pinterest.com/pin/282671314100562394/
Create a variable called texture and add downloaded texture to it. Then that texture should be include into “material”.
const texture = new THREE.TextureLoader().load('textures/wood.jpg');
const material = new THREE.MeshBasicMaterial({ map: texture });
So this is how our box finally looks like.
Final code will look like this.
let scene, camera, renderer, cube;function init() { scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75,
window.innerWidth /window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer({ antialises: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement); const geometry = new THREE.BoxGeometry();
const texture=newTHREE.TextureLoader().load('textures/wood.jpg');
const material = new THREE.MeshBasicMaterial({ map: texture }); 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);};function onWindowResize() { camera.aspect = window.innerWidth /
window.innerHeight;camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);}window.addEventListener('resize', onWindowResize, false);init();
animate();
If you want to add multiples textures for same object this is how you perform it.
var geometry = new THREE.CylinderGeometry(10, 15, 5, 5);var wood = new THREE.TextureLoader().load('textures/wood.jpg');
var grass = new THREE.TextureLoader().load('textures/grass.jpg');var materialWood = new THREE.MeshBasicMaterial({ map: wood });
var materialGrass = new THREE.MeshBasicMaterial({ map: grass });const materials = [
materialWood,
materialGrass,
materialWood
];var mesh = new THREE.Mesh(geometry, materials);
First we have to load textures from external sources. Here I have used two textures called wood and grass. Grass texture was downloaded from this link. https://www.pinterest.com/pin/351843789611496477/
Then array of materials is created and it has been passed when creating a mesh.
const materials = [
side,
top,
bottom
];
Final result would look like this.
Here I have used blue color plain to visualize the island more precisely.
Hope you grab something !!!