three学习-vscode-添加控制器监听用js02

1、main.js

//导入three
import * as THREE from "three";
//导入OrbitControls
//导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

//创建场景
const scane = new THREE.Scene();

//创建相机
const camrea = new THREE.PerspectiveCamera(
    45, //视角
    window.innerWidth / window.innerHeight, //宽高比
    0.1, //近平面,最近能看到的视角
    1000 //远平面,最远能看到的视角
);

//创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

//创建几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
//创建材质
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
//创建网格
const cube = new THREE.Mesh(geometry, material);

//将网格添加到场景中
scane.add(cube);

//设置相机位置,相机默认看向原点
camrea.position.z = 5;
camrea.position.y = 2;
camrea.position.x = 2;
camrea.lookAt(0, 0, 0);

//添加世界坐标系
const axesHelper = new THREE.AxesHelper(5);
scane.add(axesHelper);

//添加轨道控制器,renderer.domElement监听的是canvas事件
//const controls = new OrbitControls(camrea, renderer.domElement);
//也可以用body,用body的时候,css里面要设置body的宽高,因为body默认为0,监听document.body
const controls = new OrbitControls(camrea, document.body);

//渲染函数
function animate() {
    //控制器
    controls.update();
    //设置带阻尼的惯性
    controls.enableDamping = true;
    //设置阻尼系数,系数越大,惯性越小,系数小,惯性大
    controls.dampingFactor = 0.01;
    //设置旋转速度,设置自动旋转
    controls.autoRotate = true;

    requestAnimationFrame(animate);
    //旋转
    // cube.rotation.x += 0.01;
    // cube.rotation.y += 0.01;

    //渲染
    renderer.render(scane, camrea);

}

//实现动画
animate();
View Code

2、style.css

* {
    margin: 0;
    padding: 0;
}

body {
    width: 100vw;
    height: 100vh;
}

canvas {
    display: block;
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
}
View Code

 

posted @ 2024-01-31 00:03  CiscoLee  阅读(7)  评论(0编辑  收藏  举报