behavior.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. module.exports = Behavior({
  2. // 全局变量
  3. session: undefined, // 全局的VKsession对象
  4. canvas: undefined, // canvas
  5. // XRFrame相关变量
  6. xrScene: undefined, // xr-frame 的场景
  7. xrCamera: undefined, // xr-frame 的相机
  8. xrFrameReady: undefined, // xr-frame初始化完毕
  9. // WebGL相关
  10. camera: undefined, // 主要相机
  11. // ThreeJs 相关变量
  12. gl: undefined, // 全局gl对象
  13. THREE: undefined, // THREE 对象
  14. // 全局 data
  15. data: {
  16. domWidth: 0,
  17. domHeight: 0,
  18. width: 0, // canvas大小
  19. height: 0, // canvas大小
  20. widthScale: 1, // canvas宽度缩放值
  21. heightScale: 1, // canvas高度缩放值
  22. cameraPosition: 0, // 相机朝向,默认后置摄像头
  23. },
  24. methods: {
  25. onReady() {
  26. // 获取canvas
  27. wx.createSelectorQuery()
  28. .select('#canvas')
  29. .node()
  30. .exec(res => {
  31. this.canvas = res[0].node
  32. // 运算画布大小
  33. this.calcCanvasSize()
  34. // 页面自定义初始化
  35. if (this.init) this.init()
  36. })
  37. },
  38. calcCanvasSize() {
  39. const info = wx.getWindowInfo()
  40. const pixelRatio = info.pixelRatio
  41. const width = info.windowWidth * this.data.widthScale * pixelRatio
  42. const height = info.windowHeight * this.data.heightScale * pixelRatio
  43. // 存在 webgl Canvas的情况下,写入大小
  44. if (this.canvas) {
  45. this.canvas.width = width
  46. this.canvas.height = height
  47. }
  48. console.log(`canvas size: width = ${width} , height = ${height}`)
  49. this.setData({
  50. width,
  51. height,
  52. domWidth: info.windowWidth * this.data.widthScale,
  53. domHeight: info.windowHeight * this.data.heightScale,
  54. })
  55. },
  56. // 前后摄像头
  57. switchCamera() {
  58. if (this.session.config) {
  59. const config = this.session.config
  60. let cameraPosNext
  61. if (this.data.cameraPosition === 0) {
  62. cameraPosNext = 1
  63. } else {
  64. cameraPosNext = 0
  65. }
  66. config.cameraPosition = cameraPosNext
  67. this.session.config = config
  68. this.setData({
  69. cameraPosition: cameraPosNext
  70. })
  71. }
  72. },
  73. // 限帧逻辑
  74. initLoop() {
  75. // 限制调用帧率,暂时去掉
  76. const fps = 30
  77. const fpsInterval = 1000 / fps
  78. let last = Date.now()
  79. const session = this.session
  80. // 逐帧渲染
  81. const onFrame = timestamp => {
  82. try {
  83. const now = Date.now()
  84. const mill = now - last
  85. // 经过了足够的时间
  86. if (mill > fpsInterval) {
  87. last = now - (mill % fpsInterval) // 校正当前时间
  88. this.loop()
  89. }
  90. } catch (e) {
  91. console.error(e)
  92. }
  93. session.requestAnimationFrame(onFrame)
  94. }
  95. session.requestAnimationFrame(onFrame)
  96. },
  97. },
  98. })