


A brief analysis of how to use threejs in small programs
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!
#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! ! !
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
I found that this CubeGeometry has been renamed long ago
Update log: https://github.com/mrdoob/three.js/wiki/Migration-Guide
##Question 2 addEventListener error
_canvas.addEventListener('webglcontextlost', onContextLost, false); _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
Question 3 There is a problem with canvas type
const context = _canvas.getContext('webgl', contextAttributes);
const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
interface EXT_blend_minmax { const GLenum MIN_EXT = 0x8007; const GLenum MAX_EXT = 0x8008; };
2. Use TextureLoader
Solution to error
Problem 1 createElementNS
##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)
To solve the problem, you can use Texture
to solve the error report
Problem 1 addEventListener
WeChat 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(输出展示)
上图中,下面的实线是实际显示器的亮度和颜色的系数图,如果没有误差,是不需要gamma校正的, 但实际上线性空间里计算出来的光照的中间亮度部分会被压暗,所以需要经过Gamma校正,调高原有的值进行显示。
参考文章
https://www.cnblogs.com/guanzz/p/7416821.html
https://cloud.tencent.com/developer/article/1543647
展示
5 真机调试
真机调试2.0支持canvas
解决问题
问题1 模型太大
只能放到线上,放到GitHub上,可以访问raw.githubusercontent.com请求到资源
问题2 githubusercontent访问不稳定,经常挂
放到码云上,码云同样有raw地址可以访问到资源
问题3 码云大于1m的资源需要登录
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

With the continuous development of Internet technology, the needs of Web applications are no longer limited to traditional 2D page display and data interaction. Now more and more applications need to use 3D visualization technology to present data and scenes, such as 3D games, 3D modeling, physical simulation, etc. In this article, we will introduce how to create a 3D visualization application using PHP and Three.js. We will explain in detail from three aspects: First, we will explain the basic concepts of Three.js and how to use it in web applications.

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.
