一、基本场景配置
1、创建场景
const scene = new THREE.Scene(); //创建场景
2、创建并配置相机参数
各参数详情参考 threejs官方文档
// THREE.PerspectiveCamera创建一个透视相机对象
const camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
camera.position.set(200, 200, 200);
3、生成渲染实例
构造器WebGLRenderer详细参数参考Threejs官方文档
const container = threeRef.current; //被渲染的元素
const width = container.clientWidth;
const height = container.clientHeight;
const renderer = new THREE.WebGLRenderer({
antialias: true, //开启锯齿
});
renderer.setSize(width, height); //设置宽高
renderer.setPixelRatio(window.devicePixelRatio);//设置设备像素比率,防止Canvas画布输出模糊。
//renderer.setClearColor('#af3', .5) //背景颜色,默认黑色
container.appendChild(renderer.domElement); //生成的渲染的实例,放到对应的dom容器里面
renderer.render(scene, camera); //执行渲染操作
4、光源设置
// 正面光源
var directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight.position.set(500, 500, 500);
scene.add(directionalLight);
// 背面光源
var directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight2.position.set(-500, -500, -500);
scene.add(directionalLight2);
//环境光
var ambient = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambient);
5、辅助坐标系配置
const axisHelper = new THREE.AxesHelper(200)
scene.add(axisHelper)//插入辅助线长度为200的坐标系
6、创建轨道控制器(OrbitControls)
(1)构建轨道控制器,并传入相机与渲染的容器
Orbitcontrols(轨道控制器)可以使得相机围绕目标进行轨道运动。
- 旋转:拖动鼠标左键
- 缩放:滚动鼠标中键
- 平移:拖动鼠标右键
const controls = new OrbitControls(camera, container);
// controls.enableZoom = false; //禁用缩放
// controls.enableRotate = false; //禁用旋转
// controls.enablePan = false; //禁用平移
// controls.update();
(2)设置动态渲染函数并调用
const animate = function () {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
效果:
二、地球创建
1、创建贴图球几何体
地球贴图earthImg:
// r:地球半径
function createSphereMesh(r) {
// TextureLoader创建一个纹理加载器对象,可以加载图片作为纹理贴图
var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load(earthImg);//加载纹理贴图
var geometry = new THREE.SphereBufferGeometry(r, 40, 40);
//材质对象Material
var material = new THREE.MeshLambertMaterial({
map: texture,//设置地球贴图
});
var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
return mesh
}
// 创建一个地球总对象earthGroup
function createEarth(R) {
var earthGroup = new THREE.Group();//地球组对象
earthGroup.add(createSphereMesh(R));//球体Mesh插入earthGroup中
});
return earthGroup;
}
var earth = createEarth(R);// 创建地球
scene.add(earth) //添加地球模型到场景中
效果: