Skip to content

光源对物体表面影响

🕒 Published at:

在上一个案例中 我们采用了基础网格材质 MeshBasicMaterial 来实现了一个简单的3D场景,但是这个材质是没有光照的,所以我们需要一个光源来照亮我们的场景,这样才能看到我们的3D场景。

准备工作

我们需要一个光源,来照亮我们的场景,这里我们使用一个点光源 PointLight。为了更好的观察光照的影响,我们使用 漫反射网格材质;MeshLambertMaterial

官方 说明 MeshLambertMaterial是 一种非光泽表面的材质,没有镜面高光。

那么在上个博客的基础上我们只需换一下材质和添加一个光源就可以达到以下这种效果了。

光源代码

js
const pointLight = new THREE.PointLight(0xffffff, 1.0);
pointLight.decay = 0.0;//光源光照强度不随距离改变衰减
//点光源位置
// pointLight.position.set(400, 0, 0);//点光源放在x轴上
pointLight.position.set(400, 200, 300);//偏移光源位置,观察渲染效果变化
scene.add(pointLight); //点光源添加到场景中

效果

代码实现

js
// 引入three.js
import * as THREE from 'three';
/**
 * 创建3D场景对象Scene
 */
const scene = new THREE.Scene();

/**
 * 创建网格模型
 */
//创建一个长方体几何对象Geometry
const geometry = new THREE.BoxGeometry(100, 100, 100);
//材质对象Material
// 基础网格材质 MeshBasicMaterial 不受光照影响
// 漫反射网格材质;MeshLambertMaterial
const material = new THREE.MeshLambertMaterial({
    color: 0x00ffff, //设置材质颜色
});
const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
scene.add(mesh); //网格模型添加到场景中

// AxesHelper:辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);



/**
 * 光源设置
 */
//点光源
const pointLight = new THREE.PointLight(0xffffff, 1.0);
pointLight.decay = 0.0;//光源光照强度不随距离改变衰减
//点光源位置
// pointLight.position.set(400, 0, 0);//点光源放在x轴上
pointLight.position.set(400, 200, 300);//偏移光源位置,观察渲染效果变化
scene.add(pointLight); //点光源添加到场景中




// width和height用来设置Three.js输出的Canvas画布尺寸(像素px)
const width = 800; //宽度
const height = 500; //高度
/**
 * 透视投影相机设置
 */
// 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000:远裁截面
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
camera.position.set(292, 223, 185); //相机在Three.js三维坐标系中的位置
camera.lookAt(0, 0, 0); //相机观察目标指向Three.js坐标系原点

/**
 * 创建渲染器对象
 */
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
renderer.render(scene, camera); //执行渲染操作
//three.js执行渲染命令会输出一个canvas画布,也就是一个HTML元素,你可以插入到web页面中
document.body.appendChild(renderer.domElement);