THREEJS Material

ASHABB ReactJS & ThreeJS
7 min readAug 7, 2023

--

Title: “Unveiling the World of Three.js Materials: A Comprehensive Guide”

Photo by Andrew Ridley on Unsplash

1. Title

2. Description

3. Snippet

4. Explanation

5. Full code

6. Output

7. Summary

8. Next and Previous Blog

2. Description

Dive into the exciting realm of Three.js materials in this comprehensive blog. Explore the diverse range of materials, from basic to advanced, that can transform your 3D scenes into captivating visual experiences. Learn how to create realistic surfaces, apply textures, and master shading techniques. Whether you’re a beginner or an experienced developer, this guide will unlock the secrets of Three.js materials and help you craft stunning visuals for your web projects. Get ready to elevate your 3D graphics with the power of materials!

here’s a list of some common types of materials available in Three.js:

Sure, here’s a list of some common types of materials available in Three.js:

1. MeshBasicMaterial: A basic material that doesn’t respond to lighting, providing flat shading and a consistent color across the object.

2. MeshLambertMaterial: A material that reacts to light in a Lambertian manner, providing diffuse reflection and smooth shading.

3. MeshPhongMaterial: A material that simulates specular and shiny surfaces, reacting to light with highlights and reflections.

4. MeshStandardMaterial: A physically based material with realistic shading, offering parameters like roughness and metalness for controlling the surface appearance.

5. MeshPhysicalMaterial: An extension of MeshStandardMaterial with additional features like clear coat and transmission for advanced realism.

6. MeshToonMaterial: A simplified shading model that creates a flat, cartoon-like appearance.

7. MeshNormalMaterial: A material that displays object normals as colors, useful for debugging and visualization.

8. MeshDepthMaterial: A material that renders objects based on their distance from the camera, useful for depth-based effects.

9. MeshDistanceMaterial: A material that colors objects based on their distance from a given point, creating unique effects.

10. ShadowMaterial: A material for rendering shadows, used in combination with a depth texture in shadow maps.

11. LineBasicMaterial: A basic material for lines, similar to MeshBasicMaterial but for line geometries.

12. LineDashedMaterial: A material for dashed lines, offering control over dash and gap lengths.

13. PointsMaterial: A material for rendering points, typically used for particle systems.

14. SpriteMaterial: A material for rendering sprites, useful for 2D elements that always face the camera.

15. ShaderMaterial: A material that allows you to define custom shaders to control the appearance of objects.

These are just a few examples of the many material types available in Three.js. Each material type offers unique properties and characteristics that can be used to achieve different visual effects and appearances in your 3D scenes.

3. Snippet and 4. Explanation

MeshBasicMaterial: Simplified Surfaces for Creative Flexibility

// Create a basic material
const basicMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000, // Red color
wireframe: true // Enable wireframe mode
});

// Create a geometry (e.g., a cube)
const geometry = new THREE.BoxGeometry(1, 1, 1);

// Create a mesh using the geometry and material
const cube = new THREE.Mesh(geometry, basicMaterial);

// Add the cube to the scene
scene.add(cube);

In the world of Three.js materials, the MeshBasicMaterial stands as a versatile choice that offers both simplicity and creative freedom. While it might not replicate the intricacies of real-world lighting and shading like some other materials, it’s an essential tool for achieving specific visual effects and styles.

At its core, the MeshBasicMaterial provides the following properties:

1. Color: This property defines the base color of the material. It’s a straightforward way to give objects a flat and consistent color across their surfaces.

2. Map: By applying a texture map, you can introduce intricate patterns, images, or designs to your objects. This is a common technique for adding detail and complexity to simple shapes.

3. Opacity and Transparent: These properties control the transparency of the material. You can create see-through objects or gradually fade them out using opacity values.

4. Wireframe: Enabling the wireframe mode displays the object as a mesh of wireframe lines, making it a great choice for visualizing the underlying structure of your geometries.

The MeshBasicMaterial’s strength lies in its simplicity. It’s perfect for creating flat, stylized visuals, like cartoons or diagrams. While it doesn’t respond to complex lighting setups, it’s ideal for scenarios where you want objects to have a consistent appearance, without the nuances of shadows or highlights. This material type is particularly useful when you’re prototyping, experimenting, or aiming for a specific artistic style.

Moreover, the MeshBasicMaterial can be a valuable companion when combined with other materials. By layering different materials on the same object, you can achieve intricate designs that integrate both realism and stylization.

In the world of digital art and 3D graphics, the MeshBasicMaterial offers an essential toolkit for expressing creativity in a simplified yet impactful manner. Its properties empower you to craft visuals that range from minimalist elegance to bold and vibrant designs, giving you the means to shape your 3D world according to your artistic vision.

MeshStandardMaterial: Realistic Surfaces in Three.js

// Create a standard material
const standardMaterial = new THREE.MeshStandardMaterial({
color: 0x2194ce, // Blue color
roughness: 0.4,
metalness: 0.7
});

// Create a geometry (e.g., a sphere)
const geometry = new THREE.SphereGeometry(1, 32, 32);

// Create a mesh using the geometry and material
const sphere = new THREE.Mesh(geometry, standardMaterial);

// Add the sphere to the scene
scene.add(sphere);

This code creates a blue sphere with standard material, and you can experiment with different values for properties like roughness and metalness to observe how they affect the appearance of the material.

The MeshStandardMaterial is a pivotal tool in Three.js for crafting lifelike 3D visuals. It’s designed to mimic the interaction of light with various materials, making objects appear more authentic and immersive. This material type introduces properties that allow you to simulate intricate lighting scenarios and create stunningly realistic surfaces.

Key properties of the MeshStandardMaterial:

  1. Color: Set the base color of the material. This forms the foundation of the object’s appearance.
  2. Roughness: Control the microsurface roughness. A higher value results in a matte finish, while lower values produce smoother and shinier surfaces.
  3. Metalness: Determine the metallicity of the material. Higher values create a metallic look with strong reflections, while lower values mimic non-metallic materials.
  4. Normal Map: Apply a normal map texture to simulate fine surface details without changing the geometry.
  5. Emissive: Make parts of the object appear self-illuminated, adding an extra layer of realism.
  6. EnvMap: Use an environment map for reflections and global illumination, enhancing the material’s interaction with its surroundings.
  7. Clear Coat: Add an extra layer with clear coat reflections, simulating a protective layer on the material’s surface.
  8. Transmission: Simulate the transparency and translucency of materials like glass or water.

5. Full code

<html lang="en">

<head>
<title>THREEJS Material</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>

<style>
body {
background-color: grey
}

html,
body {
margin: 0;
height: 100%;
}

#canvas {
width: 100%;
height: 100%;
display: block;
color: rgb(40, 63, 141);
}
</style>

</head>

<body>
<canvas id="canvas"></canvas>
<script type="importmap">
{
"imports": {
"three": "../threeJS/build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from '../threeJS/examples/jsm/controls/OrbitControls.js';
import * as DAT from '../threeJS/newadded/DatGUI.js';
import { Stats } from "../threeJS/newadded/Stats.js";

//---gui---//
var gui;
gui = new DAT.GUI();
var lightGui = false;
var statsGui = true;
gui.close();

// three var
var canvas, renderer, scene, camera, controls, stats;

function init() {
canvas = document.getElementById('canvas');

renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(window.innerWidth, window.innerHeight);
stats = Stats();
statsGui && document.body.appendChild(stats.dom);

scene = new THREE.Scene();
scene.background = new THREE.Color('black');
scene.fog = new THREE.Fog(0xffffff, 0, 750);

const axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);

const ambientLight = new THREE.AmbientLight(0xffffff, 0.7)
scene.add(ambientLight)

camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = 5;
camera.position.z = 7;


controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.6;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2.02;
controls.minDistance = 10;
controls.maxDistance = 1000;
controls.update();

/*-------------light-------------*/
const light = new THREE.DirectionalLight(0xFFFFFF);
scene.add(light)
/*-------------floor-------------*/
const floorGeometry = new THREE.PlaneGeometry(10, 10);
const floorMaterial = new THREE.MeshStandardMaterial({
color: '#777777',
metalness: 0.2,
roughness: 0.4,
envMapIntensity: 0.5,
side: THREE.DoubleSide

});
const floor = new THREE.Mesh(floorGeometry, floorMaterial)
floor.receiveShadow = true
floor.rotation.x = - Math.PI * 0.5
floor.position.set(0, 0, 0)
scene.add(floor)

/*-------------Objects-------------*/
const material = new THREE.MeshStandardMaterial(
{
side: THREE.DoubleSide,
color: 0x2194ce, // Blue color
roughness: 0.4,
metalness: 0.7
}
)

const sphere = new THREE.Mesh(
new THREE.SphereGeometry(1, 16, 16),
material
)
sphere.position.x = -2
sphere.position.y = 2

const plane = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2),
material
)
plane.position.x = 2
plane.position.y = 2

scene.add(sphere, plane)

window.addEventListener('resize', function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
}


function animate() {
requestAnimationFrame(animate)
renderer.render(scene, camera);
stats.update();
}
init()
animate();
</script>
</body>

</html>

6. Output

7. Summary

In today’s blog, we delved into the captivating world of Three.js materials, exploring two distinct material types that have a profound impact on your 3D scenes. The MeshBasicMaterial offers a simplified approach, allowing for creative flexibility with properties like color, opacity, and wireframe. On the other hand, the MeshStandardMaterial shines as a powerhouse for crafting realism, presenting properties such as roughness, metalness, emissive effects, and more.

Understanding these materials empowers creators to transform concepts into visual masterpieces. With the MeshBasicMaterial, you can achieve minimalist elegance or bold styles. The MeshStandardMaterial, in contrast, invites you to replicate real-world surfaces and lighting interactions, enabling lifelike visuals that draw users into immersive experiences.

As we journey deeper into the realm of Three.js materials, we unlock a realm of creative potential. These materials, each with its own unique characteristics, are essential tools for sculpting the aesthetic and atmosphere of your digital landscapes. Whether you’re an artist, developer, or enthusiast, mastering these materials is a step towards realizing your 3D vision with unparalleled realism and ingenuity.

8. Previous Blog

previous blog: THREEJS Debug UI

do visit us on Instagram & Threads

--

--