小程序版 Three.js 入门 Demo(完整可运行)

第一步:准备项目(前提)

  1. 确保你的小程序项目已安装 threejs-miniprogram

    复制代码
    # 在项目根目录执行
    npm install threejs-miniprogram
    # 然后在微信开发者工具 → 工具 → 构建 npm
  2. 新建 / 替换 pages/index 下的 3 个文件:

第二步:index.wxml(仅需一个 Canvas)

复制代码
<!-- 必须加 type="webgl",小程序 3D 渲染核心 -->
<canvas 
  type="webgl" 
  id="cube-canvas" 
  style="width: 100%; height: 100vh;"
/>

第三步:index.wxss(极简样式)

复制代码
/* 去掉默认边距,让 Canvas 占满屏幕 */
page {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100vh;
}

第四步:index.js(核心代码,逐行注释)

复制代码
// 引入小程序版 Three.js 核心方法
import { createScopedThreejs } from 'threejs-miniprogram';

Page({
  data: {},
  // 页面渲染完成后初始化(小程序生命周期)
  onReady() {
    this.initThreeJS();
  },

  // 初始化 Three.js 核心逻辑
  initThreeJS() {
    // 1. 获取小程序 Canvas 节点(关键:小程序特有)
    const query = wx.createSelectorQuery().in(this);
    query.select('#cube-canvas').node((res) => {
      // 容错:防止 Canvas 获取失败
      if (!res || !res.node) {
        wx.showToast({ title: 'Canvas初始化失败', icon: 'none' });
        return;
      }
      const canvas = res.node;

      // 2. 创建小程序专属 Three.js 实例(核心区别:网页版不用这步)
      const THREE = createScopedThreejs(canvas);

      // 3. 适配高清屏(小程序/手机必备)
      const dpr = wx.getWindowInfo().pixelRatio;
      canvas.width = canvas.width * dpr;
      canvas.height = canvas.height * dpr;

      // ==================== 核心 5 件套(和网页版完全一致) ====================
      // ① 场景:3D 容器
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0xf0f0f0); // 浅灰色背景

      // ② 相机:透视相机
      const camera = new THREE.PerspectiveCamera(
        75,
        canvas.width / canvas.height, // 宽高比
        0.1,
        1000
      );
      camera.position.z = 5; // 相机后移,能看到立方体

      // ③ 渲染器:绑定 Canvas 节点
      const renderer = new THREE.WebGLRenderer({
        canvas: canvas,
        antialias: true // 抗锯齿
      });
      renderer.setSize(canvas.width / dpr, canvas.height / dpr); // 适配 dpr

      // ④ 创建立方体(几何 + 材质)
      const geometry = new THREE.BoxGeometry(1, 1, 1); // 立方体几何
      const material = new THREE.MeshStandardMaterial({
        color: 0x3498db,    // 蓝色
        metalness: 0.2,     // 轻微金属质感
        roughness: 0.4      // 哑光
      });
      const cube = new THREE.Mesh(geometry, material); // 组合成物体
      scene.add(cube); // 加到场景

      // ⑤ 灯光(必加!否则立方体黑的)
      const ambientLight = new THREE.AmbientLight(0xffffff, 1); // 环境光
      scene.add(ambientLight);
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); // 方向光
      directionalLight.position.set(3, 3, 3); // 灯光位置
      scene.add(directionalLight);

      // ==================== 动画循环(小程序版适配) ====================
      const animate = () => {
        // 旋转立方体
        cube.rotation.y += 0.01;
        cube.rotation.x += 0.01;

        // 渲染场景+相机
        renderer.render(scene, camera);

        // 小程序版 requestAnimationFrame(绑定 Canvas)
        canvas.requestAnimationFrame(animate);
      };
      // 启动动画
      animate();

      // ==================== 页面卸载时销毁资源(小程序性能优化) ====================
      this.onUnload(() => {
        renderer.dispose(); // 销毁渲染器,释放内存
      });
    }).exec();
  }
});

第五步:运行效果

  1. 微信开发者工具中编译项目;
  2. 你会看到:
    • 小程序页面全屏显示浅灰色背景;
    • 一个蓝色立方体自动旋转
    • 立方体有光影立体感,边缘光滑;
    • 完全适配手机屏幕。
相关推荐
MaCa .BaKa1 天前
44-校园二手交易系统(小程序)
java·spring boot·mysql·小程序·maven·intellij-idea·mybatis
普通人61 天前
微信小程序又双叒叕改获取头像昵称的接口了
微信小程序·小程序·notepad++
做cv的小昊2 天前
结合代码读3DGS论文(12)——NeurIPS 2024 Spotlight 3DGS经典Backbone工作3DGS-MCMC论文及代码解读
论文阅读·计算机视觉·3d·图形渲染·游戏开发·计算机图形学·3dgs
云飞云共享云桌面2 天前
SolidWorks三维设计不用单独买电脑,1台服务器10个设计用
运维·服务器·数据库·3d·电脑
于先生吖2 天前
高并发稳定运营,JAVA 动漫短剧小程序 + H5 源码
java·开发语言·小程序
2501_915921432 天前
uni-app一键生成iOS安装包并上传TestFlight全流程
android·ios·小程序·https·uni-app·iphone·webview
syncon122 天前
手机液晶显示屏薄膜电路开路短路检测及液晶线路激光修复原理
科技·3d·制造
CHU7290352 天前
旧衣新生之旅:旧衣服回收小程序的环保实践
小程序
闹小艾2 天前
2026 知识付费线上课程小程序 SaaS制作平台深度评测:6 大维度拆解,教你选对不踩坑
大数据·小程序
一只小白菜2 天前
Taro 4 + 支付宝小程序:Vite 编译报错 chunk.type undefined 的终极解决方案
小程序·taro