微信小程序之ThreeJS的使用:获取两个canvas并显示

前言

开发过程中需要实现小程序同时展示两个模型,并且有各自的操控事件。

注:本人使用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文件,所以一定要注意小程序分包。

posted @ 2021-04-14 14:23  bugSource  阅读(1403)  评论(0编辑  收藏  举报