分类: Java
2022-11-25 16:00:21
//导入包
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import * as dat from 'dat.gui';
import Stats from 'three/addons/libs/stats.module.js';
let scene,camera,renderer
//场景
scene = new THREE.Scene();
//坐标抽
const axesHelper = new THREE.AxesHelper(20);
scene.add(axesHelper);
//场景贴图
const sphereTexture = new THREE.CubeTextureLoader().setPath('./textures/course/environmentMaps/0/');
const envTexture= sphereTexture.load([
'px.jpg',
'nx.jpg',
'py.jpg',
'ny.jpg',
'pz.jpg',
'nz.jpg'
]);
//场景添加背景
scene.background = envTexture;
//场景的物体添加环境贴图(无默认情况使用)
scene.environment = envTexture;
const sphereGeometry = new THREE.SphereGeometry(5, 30, 30);
const sphereMaterial = new THREE.MeshStandardMaterial({
roughness: 0,//设置粗糙程度
metalness: 1,//金属度
envMap:envTexture,
});
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
scene.add(sphere);
//光照
const ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.05);
directionalLight.position.set(10,10,10);
directionalLight.lookAt(scene.position);
scene.add( directionalLight );
//相机
camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
1,
2000,
);
camera.position.set(10,10,20);
camera.lookAt(scene.position);
scene.add(camera);
//渲染器
renderer = new THREE.WebGLRenderer({
//防止锯齿
antialias: true,
});
renderer.setSize(window.innerWidth, window.innerHeight);
// renderer.setClearColor(0xb9d3ff, 1);
document.body.appendChild(renderer.domElement);
//鼠标控制器
const controls = 跟单网gendan5.comnew OrbitControls(camera, renderer.domElement);
//阻尼 必须在 render函数调用 controls.update();
controls.dampingFactor = true;
controls.autoRotate=true
const stats=new Stats()
document.body.appendChild(stats.dom);
function render () {
renderer.render(scene, camera);
requestAnimationFrame(render);
controls.update();//调用
stats.update()
}
render();
//全屏操作
window.addEventListener('dblclick', () => {
//查询是否全屏
let isFullScene = document.fullscreenElement;
console.log(isFullScene);
if (!isFullScene) {
renderer.domElement.requestFullscreen();
}
else {
document.exitFullscreen();
}
})
//自适应
window.addEventListener('resize', () => {
//宽高比
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);//设置像素比
})
//界面操作
const gui = new dat.GUI();
//操作物体位置
gui
.add(sphere.position, 'x')
.min(0)
.max(10)
.step(0.1)
.name('X轴移动')
.onChange((value) => {
console.log('修改的值为' + value);
})
.onFinishChange((value) => {
console.log('完全停止' + value);
});
//操作物体颜色
const colors = {
color: '#0000ff',
};
gui
.addColor(colors, 'color')
.onChange((value) => {
//修改物体颜色
sphere.material.color.set(value);
});