【Three.js】前端从零开始学习 threejs:创建第一个 threejs3D 页面

课程和学习大纲

对应的课程在这里:Threejs教程、2023最新最全最详细Threejs教程、零基础Threejs最详细教程(已完结)

学习知识要点思维导图:

官网和文档的使用

three.js 官网

如果无法访问,可以下载国内大佬的镜像跑起来就行 threejs-code-public

npm i 下载依赖后启动 npm run start 启动就可以啦!

官方编辑器直接点击,后续拿来做测试使用。

创建第一个 threejs3D 页面

html 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>My first three.js app</title>
    <style>
      body {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <script type="module">
      import * as THREE from 'https://unpkg.com/three/build/three.module.js';

      // Our Javascript will go here.
      // 创建场景:场景是所有物体的容器
      const scene = new THREE.Scene();
      // 创建相机:相机是用户眼睛
      const camera = new THREE.PerspectiveCamera(); // 透视相机
      // 调整相机位置
      camera.position.z = 10; // 将相机向后移动10个单位
      camera.position.y = 5; // 将相机向上移动5个单位

      // 创建一个立方体:BoxGeometry 是一个立方体的几何体
      const geometry = new THREE.BoxGeometry();
      // 创建一个材质:MeshBasicMaterial是一种简单的材质,不受光照影响
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

      // 创建一个立方体网格:Mesh是一个物体,它由几何体和材质组成
      const cube = new THREE.Mesh(geometry, material);
      cube.position.set(0, 3, 0);
      // 将立方体网格添加到场景中
      scene.add(cube);

      // 创建渲染器:渲染器将场景和相机渲染到画布上
      const renderer = new THREE.WebGLRenderer();
      // 在页面中添加渲染器
      document.body.appendChild(renderer.domElement);
      // 设置渲染器的大小
      renderer.setSize(window.innerWidth, window.innerHeight);

      // 添加网格地面
      const gridHelper = new THREE.GridHelper(10, 10);
      scene.add(gridHelper);

      // 调用渲染
      renderer.render(scene, camera);

      // 创建一个动画
      function animate() {
        requestAnimationFrame(animate); // requestAnimationFrame: 浏览器会在下一次重绘之前调用指定的回调函数
        // 使立方体网格旋转
        // cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
        // 调用渲染
        renderer.render(scene, camera);
      }
      animate();
    </script>
  </body>
</html>
相关推荐
ly76897 分钟前
CSS 从入门到进阶:系统掌握现代网页样式与布局
前端·css
xiaoxiangsiyan16 分钟前
现代大型虚拟化智慧园区整体架构EVPN‑VXLAN落地全解
运维·网络·学习·架构
SWAGGY..27 分钟前
【C++初阶】:(15)模板进阶--从非类型参数到模板特化与分离编译
java·服务器·前端
YHHLAI28 分钟前
从「跑分」到「干活」:Benchmark 与 GPT 5.6 的两种叙事
大数据·前端·人工智能·react.js·前端框架
BigTopOne32 分钟前
ArLiveLite 用到的 C++/JNI 技术点
前端
BigTopOne32 分钟前
ArLiveLite 技术架构-Lite
前端
BigTopOne37 分钟前
ArLiveLite-具体功能
前端
mlidongfeng39 分钟前
[AI][昇腾950]TP(Transport Layer,传输层)学习笔记
笔记·学习
BigTopOne41 分钟前
ArLiveLite -具体功能
前端
Sherotree43 分钟前
理解 JWT:三段分别是什么
前端·ai·开源