流浪のwolf

卷帝

导航

threejs - 渲染第一个3D场景 - 旋转的正方体

1. 安装 threejs & 使用

2. 创建三要素  场景 scene 相机 camera 渲染器 render 

3. 场景 new THREE.Scene()  

相机分为 2 种  1. 透视相机 2. 正交相机 

渲染器的使用  把canvas标签渲染到body 页面

document.body.appendChild(renderer.doLement);  //  渲染canvas

renderer.render(场景scene,相机 camers); 

 

// 导入 threejs 
import * as THREE from "three";
// 创建场景 scene
const scene = new THREE.Scene();
// console.log(scene,'scene');
// 创建相机 -- 观看物体的不同视角
const camera = new THREE.PerspectiveCamera(
    45, // 视角
    window.innerWidth / window.innerHeight,  // 宽高比
    0.1,  // 近平面
    1000 // 远平面
);
// const camera1 = new THREE.OrthographicCamera();
// console.log('透视投影相机',camera); // 和人的眼睛看的东西一样 近大远小
// console.log('正投影相机',camera1);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
// console.log('渲染器',renderer);
// 置canvas画设布的尺寸  -- 设置threejs渲染区域的尺寸 像素 px
renderer.setSize(window.innerWidth,window.innerHeight); 
// domElement 就是一个 canvas 标签  结果 -- 把 canvas 渲染到了页面上
document.body.appendChild(renderer.domElement);

// 创建一个集合体 -- 正方体
const gemetry = new THREE.BoxGeometry(3,3,3);
// 创建材质 material  --- 网格基础材质
const material = new THREE.MeshBasicMaterial({
    color: 0x9ac833,  // # 使用 0x 替代  十六进制
});

// 创建网格模型 -- 就是 3D 物体了 -- 由几何体 gemetry 和 材质 material 构成
const mesh = new THREE.Mesh(gemetry,material); 
// console.log('网格',mesh);

mesh.position.set(0,10,0);  // 设置物体的位置 x y z  y 轴就是垂直的
// 把物体放到场景中间
scene.add(mesh);

// 设置相机的位置 position 
// camera.position.z = 100;  // 远距离和近距离
// camera.position.y = 50;  // 远距离和近距离
// camera.lookAt(0,10,0);
camera.lookAt(mesh.position);// 指向mesh对应的位置

// 动态的渲染函数
function animate() {
    requestAnimationFrame(animate);  // 逐帧渲染
    // 旋转
    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.01;
    renderer.render(scene,camera);
}
animate()

几何体的分类:

 几何体的颜色 == 材质 material 

 

材质的分类

 最终渲染 3D 物体  -- 网格对象

// 两个参数分别为几何体geometry、材质material
const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh

 

把网格对象添加到场景seene中 最后使用渲染器执行渲染函数 ;

 

 

物体旋转效果可以调用 rotation 调整位置 ;

posted on 2024-04-21 14:21  流浪のwolf  阅读(4)  评论(0编辑  收藏  举报