三维基础模板



// 引入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();
    }
}

 

posted @ 2023-12-28 10:41  雨落风  阅读(8)  评论(0编辑  收藏  举报