前言
開發過程中需要實現小程序同時展示兩個模型,並且有各自的操控事件。
注:本人使用uni-app進行小程序開發。
效果
實現
這里先貼上創建canvas對象的代碼。
<view class="content">
<canvas type="webgl" id="webglLeft" style="width: 100%; height: 225px;" @touchstart="touchStartLeft" @touchmove="touchMoveLeft" @touchend="touchEndLeft"></canvas>
<view sytle="height: 20px; width: 100%;background-color: #ffffff">-</view>
<canvas type="webgl" id="webglRight" style="width: 100%; height: 225px;" @touchstart="touchStartRight" @touchmove="touchMoveRight" @touchend="touchEndRight"></canvas>
</view>
其中@touchstart,@touchmove,@touchend是用來對模型進行旋轉,縮放等操作(前提是引用了 OrbitControls 插件)。
methods: {
touchStartLeft(e) {
THREELEFT.global.touchEventHandlerFactory('canvasLeft', 'touchstart')(e)
},
touchMoveLeft(e) {
THREELEFT.global.touchEventHandlerFactory('canvasLeft', 'touchmove')(e)
},
touchEndLeft(e) {
THREELEFT.global.touchEventHandlerFactory('canvasLeft', 'touchend')(e)
},
touchStartRight(e) {
THREERIGHT.global.touchEventHandlerFactory('canvasRight', 'touchstart')(e)
},
touchMoveRight(e) {
THREERIGHT.global.touchEventHandlerFactory('canvasRight', 'touchmove')(e)
},
touchEndRight(e) {
THREERIGHT.global.touchEventHandlerFactory('canvasRight', 'touchend')(e)
},
}
接下來重頭戲
首先是引用js文件
import * as THREELEFT from '@/common/threejs/three.weapp.js' //第一個threejs文件
import * as THREERIGHT from '@/common/threejs/three.weapp.second.js' //第二個threejs文件,與上面代碼一樣但名字不同
import { cubeControls } from '@/common/test-cases/cubeControls.js' //一個定義好的模型js文件
import { glbModel } from '@/common/test-cases/glbModel.js' //另一個定義好的模型js文件
接下來是獲取canvas對象節點信息
onLoad: function() {
wx.createSelectorQuery()
.in(this)
.selectAll('#webglLeft,#webglRight')
.node()
.exec((res) => {
let canvasLeftId = res[0][0].node._canvasId
const canvasLeft = THREELEFT.global.registerCanvas(canvasLeftId, res[0][0].node)
let canvasRightId = res[0][1].node._canvasId
const canvasRight = THREERIGHT.global.registerCanvas(canvasRightId, res[0][1].node)
//務必要等上面定義完之后再進行加載模型,不然運行時模型的觸摸事件會報錯,並且只能對最后加載的模型進行操控
cubeControls(canvasLeft, THREELEFT)
glbModel(canvasRight, THREERIGHT)
})
},
總結
1.請不要在意為什么效果圖明明是一上一下,代碼命名確實Left和right...
2.其他的獲取方式我也試過,最后只有這種才能實現我要的效果。
3.切記加載模型的步驟要留到最后面。
4.不難看出我這種方法引用了兩個相同的threejs文件,所以一定要注意小程序分包。