当前位置: 首页 > news >正文

WebXR教学 03 项目1 旋转彩色方块

在这里插入图片描述

一、项目结构

webgl-cube/
├── index.html
├── main.js
├── package.json
└── vite.config.js

二、详细实现步骤

  1. 初始化项目
npm init -y
npm install three vite --save-dev
  1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旋转彩色立方体</title>
    <style>
        body { margin: 0; overflow: hidden; }
        canvas { display: block; }
    </style>
</head>
<body>
    <script type="module" src="./main.js"></script>
</body>
</html>
  1. main.js
// 导入Three.js核心库
import * as THREE from 'three';

// ---------- 场景初始化 ----------
// 创建三维场景容器
const scene = new THREE.Scene();

// ---------- 相机配置 ----------
// 创建透视相机(模拟人眼视角)
const camera = new THREE.PerspectiveCamera(
    75, // 视野角度(FOV)
    window.innerWidth / window.innerHeight, // 宽高比
    0.1, // 近裁剪面(最近可见距离)
    1000  // 远裁剪面(最远可见距离)
);

// ---------- 渲染器配置 ----------
// 创建WebGL渲染器(启用抗锯齿)
const renderer = new THREE.WebGLRenderer({
    antialias: true,  // 开启抗锯齿
    alpha: true       // 开启透明背景(可选)
});
// 设置渲染器尺寸
renderer.setSize(window.innerWidth, window.innerHeight);
// 设置像素比(适配高清屏)
renderer.setPixelRatio(window.devicePixelRatio);
// 将画布添加到页面
document.body.appendChild(renderer.domElement);

// ---------- 立方体创建 ----------
// 创建立方体几何体(单位立方体)
const geometry = new THREE.BoxGeometry(1, 1, 1);

// 创建六面材质(颜色配置)
const materials = [
    new THREE.MeshBasicMaterial({ color: 0xff0000 }), // 右(+X)
    new THREE.MeshBasicMaterial({ color: 0x00ff00 }), // 左(-X)
    new THREE.MeshBasicMaterial({ color: 0x0000ff }), // 上(+Y)
    new THREE.MeshBasicMaterial({ color: 0xffff00 }), // 下(-Y)
    new THREE.MeshBasicMaterial({ color: 0xff00ff }), // 前(+Z)
    new THREE.MeshBasicMaterial({ color: 0x00ffff })  // 后(-Z)
];

// 组合几何体与材质生成网格对象
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);

// 设置相机初始位置(沿Z轴后移)
camera.position.z = 5;

// ---------- 动画循环 ----------
function animate() {
    requestAnimationFrame(animate);
    
    // 旋转动画(每秒约60帧)
    cube.rotation.x += 0.01;  // X轴旋转
    cube.rotation.y += 0.01;  // Y轴旋转
    
    // 渲染场景
    renderer.render(scene, camera);
}

// 启动动画
animate();

// ---------- 窗口响应式处理 ----------
window.addEventListener('resize', () => {
    // 更新相机参数
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    
    // 更新渲染器尺寸
    renderer.setSize(window.innerWidth, window.innerHeight);
});
  1. vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
    base: './',
    server: {
        port: 3000,
        open: true
    }
})

三、核心概念解析

Three.js三大核心要素:

Scene(场景):所有3D对象的容器

Camera(相机):观察场景的视角

Renderer(渲染器):负责将3D场景渲染到2D画布

坐标系系统:

X轴:水平方向(右正左负)

Y轴:垂直方向(上正下负)

Z轴:深度方向(屏幕外正,屏幕内负)

材质类型:

MeshBasicMaterial:基础材质(不受光照影响)

MeshPhongMaterial:光泽材质(受光照影响)

MeshStandardMaterial:PBR材质(物理渲染)

四、运行项目

npx vite

五、常见问题解决

页面空白问题:

检查控制台报错(F12打开开发者工具)

确保相机位置正确(camera.position.z = 5)

验证材质颜色值是否合法(0x开头十六进制)

性能优化建议:

// 在初始化渲染器时添加
renderer.shadowMap.enabled = true;  // 启用阴影
renderer.outputEncoding = THREE.sRGBEncoding;  // 颜色空间优化

进阶功能扩展:

// 添加轨道控制器(需额外安装)
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const controls = new OrbitControls(camera, renderer.domElement);

// 添加环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

相关文章:

  • 【每日八股】MySQL篇(一):概述
  • RabbitMQ消息队列机制与模式解析
  • 观测云产品更新 | PromQL 查询、应用性能监测、异常追踪等优化
  • Unity Shader Graph 2D - 一个简单的魔法阵激活效果
  • 前后端对接
  • Pinia 3.0 正式发布:全面拥抱 Vue 3 生态,升级指南与实战教程
  • AI学习第二,三天-Python基础
  • netty常见的面试问题整理
  • 将 SELinux 永久设置为 Permissive
  • 修改Ubuntu系统用户密码(root密码)的方法
  • 上海市计算机学会竞赛平台2025年1月月赛丙组分块序列
  • 虚拟机emulator报错
  • 怎么手动分析 InnoDB 数据存储和索引结构
  • 漏洞分析 Spring Framework路径遍历漏洞(CVE-2024-38816)
  • Spring Boot延迟执行实现
  • MySQL 简介
  • 创建React项目的三个方式
  • 大规模分布式处理系统:语言选择与任务分配机制
  • nginx容器配置fastapi服务失败
  • Mockito:Java单元测试中的模拟框架
  • 学校网站后台管理源码/搜索引擎营销名词解释
  • 学校英语网站栏目名称/广告商对接平台
  • 中国建设企业协会网站/2022年搜索引擎优化指南
  • 创业网站建设政策/app推广软文范文
  • 网站页脚需要放什么/百度指数如何提升
  • 南宁模板建站哪家好/英语seo