Home  >  Article  >  WeChat Applet  >  A brief analysis of how to use threejs in small programs

A brief analysis of how to use threejs in small programs

青灯夜游
青灯夜游forward
2021-12-24 10:21:495844browse

How to use threejs in mini program? The following article will talk with you about the method of using threejs in WeChat applet. I hope it will be helpful to you!

A brief analysis of how to use threejs in small programs

#The WeChat applet itself provides an adapted version, but the version is too old and the adaptation is incomplete. Try to manually adapt it yourself. This is the official github link for adapting threejs https://github.com/wechat-miniprogram/threejs-miniprogram

Effect display

Adapted mini program Code snippet
https://developers.weixin.qq.com/s/y5tDPImr7xvs

1. Simple use

GitHub address: https://github .com/mrdoob/three.js, pull down the entire project, and you need to modify the code later. There are already three compiled files in the build directory. Since the size exceeds 500k, the conversion from es6 to es5 will be skipped and three.module.js cannot be used. In order to facilitate debugging and see the error location, put the uncompressed three.js into the project. . Try to quote.

import * as THREE from '../libs/three.js'

Report an error! ! !

A brief analysis of how to use threejs in small programs

After testing, it was found to be a bug in the latest versions of the basic library. We reported it to WeChat official at the feedback address (https://developers.weixin.qq.com/community /develop/doc/0002ca77aa420880162d1b08d5b800), the official staff solved the problem very quickly,

In fact, it does not matter if it is not solved, lowering the version of the repository to 2.19.6 or using require import can also solve the problem

Resolve errors

Problem 1 Because the reference code is too old, a CubeGeometry error was reported

A brief analysis of how to use threejs in small programs

I found that this CubeGeometry has been renamed long ago

Update log: https://github.com/mrdoob/three.js/wiki/Migration-Guide

A brief analysis of how to use threejs in small programs

##Question 2 addEventListener error

A brief analysis of how to use threejs in small programs

WeChat applet does not have addEventListener and will automatically manage the overloading of canvas. Comment out the following code in three.js

_canvas.addEventListener('webglcontextlost', onContextLost, false);
_canvas.addEventListener('webglcontextrestored', onContextRestore, false);

Question 3 There is a problem with canvas type

A brief analysis of how to use threejs in small programs

#Looking at the code carefully, I found that _canvas.getContext reported an error here, and the type was changed to webgl.

const context = _canvas.getContext('webgl', contextAttributes);

There are two ways to use the canvas of the WeChat applet, webgl and 2d. 2d does not mean webgl2,

const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];

And there is no 2d in contextNames. Only image-related methods are used in the code. 2d. After solving the above problems, you can start running.

Display

A brief analysis of how to use threejs in small programs

When debugging on the mobile phone, a warning was found. The EXT_blend_minmax extension is not supported. Looking at the code, it is an error reported in threejs. Search carefully

MDN address: https://developer.mozilla.org/en-US/docs/Web/API/EXT_blend_minmax

I found that these are two constants, and they are in webgl2 is supported by default.

interface EXT_blend_minmax {
  const GLenum MIN_EXT = 0x8007;
  const GLenum MAX_EXT = 0x8008;
};

can be changed directly to the corresponding value in the code. If you want to remove the warning, it is around line 12551

2. Use TextureLoader

Solution to error

Problem 1 createElementNS

A brief analysis of how to use threejs in small programs##Look at the logic carefully: TextureLoader -> ; ImageLoader ->createElementNS

WeChat applet does not have createElementNS. After searching around, I found an alternative method, which is createImage of canvas. But where can I get the canvas? There is no way to create it directly. For convenience, I can directly create it in Pass it in when new TextureLoader. Note that the first parameter is meaningful. Just pass it empty.

const texture = new THREE.TextureLoader(undefined, canvas)

Display

To solve the problem, you can use Texture

A brief analysis of how to use threejs in small programs

3. Use OrbitControls

to solve the error report

Problem 1 addEventListener

A brief analysis of how to use threejs in small programsWeChat applet does not have addEventListener, but you can bind events on the canvas, carefully look at the point event and the events corresponding to the applet

contextmenu // 鼠标右键
wheel // 滚轮滚动
keydown // 键盘事件
// 需要进行适配的
pointerdown  ->  touchstart
pointermove  ->  touchmove
pointerup    ->  touchend

问题2 事件触发后怎么通知OrbitControls

事件有了,怎么通知呢?两个方法没有任何联系,只能用eventbus了,eventbus可以自己写个简单的  。
index.js(触发)

  onTouchStart(e) {
    EventBus.dispatchEvent(e)
  },
  onTouchMove(e) {
    EventBus.dispatchEvent(e)
  },
  onTouchEnd(e) {
    EventBus.dispatchEvent(e)
  },

OrbitControls.js (监听)

EventBus.addEventListener( 'touchstart', onPointerDown );
EventBus.addEventListener( 'touchend', onPointerUp );
EventBus.addEventListener( 'touchmove', onPointerMove);

问题3 触摸事件触发的参数问题,小程序事件触发拿到的参数和h5拿到的数据格式不一致,需要调整。

找了半天,发现微信小游戏这边有一些适配好的东西,developers.weixin.qq.com/minigame/de…

还有这个文章里老哥自己写的库应该是按照上面微信小游戏的适配库改的developers.weixin.qq.com/community/d…

我是直接用TouchEvent,看如何改成pointEvent

问题4 无法旋转

看打印,应该是某些参数有问题,导致scope.object.position计算为NaN,

排查过程:

position -> offset -> spherical -> sphericalDelta -> clientHeight

clientHeight和clientWidth需要赋值

  canvas.clientHeight = canvas.height
  canvas.clientWidth = canvas.width;

问题4 无法缩放

看打印,还是scope.object.position计算为NaN

排查过程:

position -> offset -> spherical.radius -> scale -> pointers

发现pointerId属性缺少,小程序事件有返回identifier,就是pointerId

总共修改的属性:

1.timeStamp
2. pointerType 取touch
3. 多点触摸时点击取touches数组的最后一个
4. pointerId  identifier 多点触摸时标识是某个点击
5. clientHeight

4 使用OBJLoader

解决报错

问题1 Request和fetch为undefined

微信小程序只有wx.request,刚好上面我们发现有个XMLHttpRequest.js的适配文件,可以用,尝试后发现没法直接用,需要编译成es5。 我们第一步就拉了整个threejs项目的代码,里面有可以重新编译的命令,我们可以把XMLHttpRequest复制过去,修改使用,再进行编译, 主要修改的方法:

const request = new XMLHttpRequest();
request.open('GET', url);
request.onreadystatechange = function () {}
request.onerror()
request.send()

问题2 模型默认显示太小了,

以为是还没适配好,加载有问题,看了老半天才发现已经显示了,就是太小了, 解决方法:放大

roup.scale.set(30,30,30)

问题3 模型显示很暗,需要把灯光强度调到很高才能看清

看示例是这行代码没加

renderer.outputEncoding = THREE.sRGBEncoding;

稍微了解了一下颜色空间的概念:
线性空间: 机器对亮度的感受
非线性(Gamma): 人对亮度的感受

流程:  sRGB(导入的图片) -> linear(处理时) -> sRGB(输出展示)

A brief analysis of how to use threejs in small programs

上图中,下面的实线是实际显示器的亮度和颜色的系数图,如果没有误差,是不需要gamma校正的, 但实际上线性空间里计算出来的光照的中间亮度部分会被压暗,所以需要经过Gamma校正,调高原有的值进行显示。

参考文章

https://www.cnblogs.com/guanzz/p/7416821.html

https://cloud.tencent.com/developer/article/1543647

展示

A brief analysis of how to use threejs in small programs

5 真机调试

真机调试2.0支持canvas

1A brief analysis of how to use threejs in small programs

解决问题

问题1 模型太大

只能放到线上,放到GitHub上,可以访问raw.githubusercontent.com请求到资源

问题2 githubusercontent访问不稳定,经常挂

放到码云上,码云同样有raw地址可以访问到资源

问题3 码云大于1m的资源需要登录

1A brief analysis of how to use threejs in small programs

Finally choose to use a certain cloud, which has free space available. That is, if you don’t have your own domain name, the test domain name is only valid for one month. I just applied for a domain name before, bound it, modified the cname, uploaded the model, and it can be accessed. Apply for a free certificate, https can access it, and it’s done

Summary

Notes on adapting WeChat applet to threejs:

  • Event system, event triggering and event parameters

  • Request,

  • Attribute adaptation on document

  • Attribute adaptation on canvas

While searching for related issues, I found the following guy. Basically all the threejs packages are adapted. There is also a demo display. It is recommended to take a look at https://github.com/deepkolos/three- platformize

【Related learning recommendations: 小program development tutorial

The above is the detailed content of A brief analysis of how to use threejs in small programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete