微信小程序使用ThreeJs需要使用官方庫threejs-miniprogram ,API和原生ThreeJS基本一樣,很好上手。喜歡數(shù)字孿生或者游戲的朋友,強(qiáng)烈推薦學(xué)習(xí)ThreeJs。該庫入門簡單,官方有很多優(yōu)秀的demo可供參考,文檔(包含中英文)也比較詳細(xì)。有計劃用ThreeJS做一個動物世界,模擬原始森林里各種各樣的有趣的可愛的動物,包括它們聲音和故事。有興趣的或想加入這個計劃的朋友可以在下面留言。
1、安裝ThreeJS
npm install --save threejs-miniprogram
2、.wxml頁面
添加canvash畫布,設(shè)置寬度100%,高度設(shè)置為屏幕高度減去狀態(tài)欄高度和導(dǎo)航欄高度。
<canvas
type="webgl"
id="webgl"
style="width: 100%; height: {{screenHeight}}px;">
</canvas>
3、.js頁面
導(dǎo)入threejs,并創(chuàng)建threejs變量傳入模型中,方便使用該變量。
import {createScopedThreejs} from '../../utils/threejs/index.js'
const { renderModel } = require('../../utils/threejs/model')
const app = getApp();
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
screenHeight: app.globalData.screenHeight - app.globalData.statusBarHeight - 44
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面初次渲染完成
*/
onReady: function () {
wx.createSelectorQuery()
.select('#webgl')
.node()
.exec((res) => {
const canvas = res[0].node
// 創(chuàng)建一個與 canvas 綁定的 three.js
const THREE = createScopedThreejs(canvas)
// 傳遞并使用 THREE 變量
renderModel(canvas, THREE)
})
},
})
4、運(yùn)行效果

3d模型.png