微信小程序使用ThreeJs需要使用官方库threejs-miniprogram ,API和原生ThreeJS基本一样,很好上手。喜欢数字孪生或者游戏的朋友,强烈推荐学习ThreeJs。该库入门简单,官方有很多优秀的demo可供参考,文档(包含中英文)也比较详细。
官方代码库
https://github.com/wechat-miniprogram/threejs-miniprogram
本项目当前使用的 Three.js 版本号为 0.108.0,如要更新 threejs 版本可发 PR 修改或 fork 后自行修改。
该适配版本的 THREE 不在全局环境中,如使用 Three.js 的其他配套类库,需要自行传入 THREE 到类库中。
如在使用过程中发现有适配问题,可通过 issue 反馈或发 PR 修复。
1、安装ThreeJS
1
2
3
|
npm install --save threejs-miniprogram
|
2、.wxml页面
添加canvash画布,设置宽度100%,高度设置为屏幕高度减去状态栏高度和导航栏高度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<canvas
type="webgl"
id="webgl"
style="width: 100%; height: {{screenHeight}}px;">
</canvas>
|
3、.js页面
导入threejs,并创建threejs变量传入模型中,方便使用该变量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
import {createScopedThreejs} from '../../utils/threejs/index.js'
const { renderModel } = require('../../utils/threejs/model')
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
screenHeight: app.globalData.screenHeight - app.globalData.statusBarHeight - 44
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
wx.createSelectorQuery()
.select('#webgl')
.node()
.exec((res) => {
const canvas = res[0].node
// 创建一个与 canvas 绑定的 three.js
const THREE = createScopedThreejs(canvas)
// 传递并使用 THREE 变量
renderModel(canvas, THREE)
})
},
})
|
4、运行效果
![](/images/2022/10/18/8260d530a299bfc9afe9018813b7d9a9.png)