// 引入three.js
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; //
export const threeDimensional = (file) => {
const scene = new THREE.Scene();
//創建物體與材質
const geometry = new THREE.BoxGeometry(100, 100, 100);
const material = new THREE.MeshLambertMaterial({
color: 0x00ffff,
transparent: true,
opacity: 0.5,
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
//輔助觀察的坐標系
const axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);
// 創建點光源
const pointLight = new THREE.PointLight(0xffffff, 1, 100)
pointLight.position.set(80, 80, 80);//偏移光源位置,觀察渲染效果變化
pointLight.intensity = 3810;//光照強度
pointLight.distance = 3000;// 光的衰減
pointLight.decay = 2;//光照強度
scene.add(pointLight);
// 環境光
const light = new THREE.AmbientLight(0x404040, 4); // 柔和的白光
scene.add(light);
// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(50, 50, 50)
scene.add(directionalLight);
let Width = window.innerWidth
let Height = window.innerHeight
//渲染器和相機
const camera = new THREE.PerspectiveCamera(30, Width / Height, 0.1, 3000);
camera.position.set(800, 800, 800); //相機在Three.js三維坐標系中的位置
camera.lookAt(0, 0, 0); //相機觀察目標指向Three.js坐標系原點
//創建渲染器
const renderer = new THREE.WebGLRenderer({
antialias: true, //設置抗鋸齒
});
renderer.setSize(window.innerWidth, window.innerHeight);
//渲染的寬高
renderer.setPixelRatio(window.devicePixelRatio)
//告訴three.js瀏覽器的像素比,防止模糊
renderer.setClearColor(0x000000)
// 設置渲染器的背景色
document.getElementById("app").appendChild(renderer.domElement);
//把渲染器插入到那個標簽下
// 設置相機控件軌道控制器OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
// 修改相機指向的位置
controls.target.set(-14, -24, 10)
// 渲染循環
function animate() {
controls.update()
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
// 畫布跟隨窗口變化
window.onresize = function () {
renderer.setSize(Width, Height);
camera.aspect = Width / Height;
camera.updateProjectionMatrix();
}
}