Three.js中文网
<template>
<div id="webgl"></div>
</template>
<script setup>
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry(50, 50, 50);
const material = new THREE.MeshPhongMaterial({
color: 0xff0000,
shininess: 20,
specular: 0x444444,
transparent: true,
opacity: 0.8,
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 0, 0);
scene.add(mesh);
const axesHelper = new THREE.AxesHelper(250);
scene.add(axesHelper);
const pointLight = new THREE.PointLight(0xffffff, 1.0);
pointLight.position.set(50, 50, 50);
pointLight.intensity = 10000.0;
scene.add(pointLight);
const pointLightHelper = new THREE.PointLightHelper(pointLight, 10);
scene.add(pointLightHelper);
const ambient = new THREE.AmbientLight(0xffffff, 0.1);
scene.add(ambient);
const camera = new THREE.PerspectiveCamera();
camera.position.set(200, 200, 200);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setClearColor(0x444444, 1);
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
renderer.render(scene, camera);
document.body.appendChild(renderer.domElement);
const gui = new GUI();
gui.domElement.style.right = '0px';
gui.domElement.style.width = '300px';
gui.add(ambient, 'intensity', 0, 2.0).name('环境光强度');
gui.addColor({ color: 0x00ffff }, 'color').onChange((value) => { mesh.material.color.set(value); });
const meshFolder = gui.addFolder('模型位置');
meshFolder.add(mesh.position, 'x', 0, 180).onChange((value) => { mesh.position.x = value; });
meshFolder.add(mesh.position, 'y', 0, 180).onChange((value) => { mesh.position.y = value; });
meshFolder.add(mesh.position, 'z', 0, 180).onChange((value) => { mesh.position.z = value; });
const meshFolder2 = meshFolder.addFolder('模型位置2');
meshFolder2.add({ scale: 0 }, 'scale', [-100, 0, 100]).name('y坐标').onChange((value) => { mesh.position.y = value; });
meshFolder2.add({ scale: 0 }, 'scale', {
left: -100,
center: 0,
right: 100
}).name('位置选择').onChange((value) => {
mesh.position.x = value;
});
const obj = {
bool: false,
};
gui.add(obj, 'bool').name('是否旋转').onChange((value) => { console.log('obj.bool', value); });
function render() {
if (obj.bool) mesh.rotateY(0.01);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', function () {
renderer.render(scene, camera);
console.log('camera.position', camera.position);
});
window.onresize = function () {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
};
</script>