


A brief analysis of how to use threejs in small programs
Dec 24, 2021 am 10:21 AMHow 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);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
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
##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
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 // 鼠標(biāo)右鍵 wheel // 滾輪滾動 keydown // 鍵盤事件 // 需要進(jìn)行適配的 pointerdown -> touchstart pointermove -> touchmove pointerup -> touchend
問題2 事件觸發(fā)后怎么通知OrbitControls
事件有了,怎么通知呢?兩個(gè)方法沒有任何聯(lián)系,只能用eventbus了,eventbus可以自己寫個(gè)簡單的 。
index.js(觸發(fā))
onTouchStart(e) { EventBus.dispatchEvent(e) }, onTouchMove(e) { EventBus.dispatchEvent(e) }, onTouchEnd(e) { EventBus.dispatchEvent(e) },
OrbitControls.js (監(jiān)聽)
EventBus.addEventListener( 'touchstart', onPointerDown ); EventBus.addEventListener( 'touchend', onPointerUp ); EventBus.addEventListener( 'touchmove', onPointerMove);
問題3 觸摸事件觸發(fā)的參數(shù)問題,小程序事件觸發(fā)拿到的參數(shù)和h5拿到的數(shù)據(jù)格式不一致,需要調(diào)整。
找了半天,發(fā)現(xiàn)微信小游戲這邊有一些適配好的東西,developers.weixin.qq.com/minigame/de…
還有這個(gè)文章里老哥自己寫的庫應(yīng)該是按照上面微信小游戲的適配庫改的developers.weixin.qq.com/community/d…
我是直接用TouchEvent,看如何改成pointEvent
問題4 無法旋轉(zhuǎn)
看打印,應(yīng)該是某些參數(shù)有問題,導(dǎo)致scope.object.position計(jì)算為NaN,
排查過程:
position -> offset -> spherical -> sphericalDelta -> clientHeight
clientHeight和clientWidth需要賦值
canvas.clientHeight = canvas.height canvas.clientWidth = canvas.width;
問題4 無法縮放
看打印,還是scope.object.position計(jì)算為NaN
排查過程:
position -> offset -> spherical.radius -> scale -> pointers
發(fā)現(xiàn)pointerId屬性缺少,小程序事件有返回identifier,就是pointerId
總共修改的屬性:
1.timeStamp 2. pointerType 取touch 3. 多點(diǎn)觸摸時(shí)點(diǎn)擊取touches數(shù)組的最后一個(gè) 4. pointerId identifier 多點(diǎn)觸摸時(shí)標(biāo)識是某個(gè)點(diǎn)擊 5. clientHeight
4 使用OBJLoader
解決報(bào)錯
問題1 Request和fetch為undefined
微信小程序只有wx.request,剛好上面我們發(fā)現(xiàn)有個(gè)XMLHttpRequest.js的適配文件,可以用,嘗試后發(fā)現(xiàn)沒法直接用,需要編譯成es5。 我們第一步就拉了整個(gè)threejs項(xiàng)目的代碼,里面有可以重新編譯的命令,我們可以把XMLHttpRequest復(fù)制過去,修改使用,再進(jìn)行編譯, 主要修改的方法:
const request = new XMLHttpRequest(); request.open('GET', url); request.onreadystatechange = function () {} request.onerror() request.send()
問題2 模型默認(rèn)顯示太小了,
以為是還沒適配好,加載有問題,看了老半天才發(fā)現(xiàn)已經(jīng)顯示了,就是太小了, 解決方法:放大
roup.scale.set(30,30,30)
問題3 模型顯示很暗,需要把燈光強(qiáng)度調(diào)到很高才能看清
看示例是這行代碼沒加
renderer.outputEncoding = THREE.sRGBEncoding;
稍微了解了一下顏色空間的概念:
線性空間: 機(jī)器對亮度的感受
非線性(Gamma): 人對亮度的感受
流程: ?sRGB(導(dǎo)入的圖片) -> linear(處理時(shí)) -> sRGB(輸出展示)
上圖中,下面的實(shí)線是實(shí)際顯示器的亮度和顏色的系數(shù)圖,如果沒有誤差,是不需要gamma校正的, 但實(shí)際上線性空間里計(jì)算出來的光照的中間亮度部分會被壓暗,所以需要經(jīng)過Gamma校正,調(diào)高原有的值進(jìn)行顯示。
參考文章
https://www.cnblogs.com/guanzz/p/7416821.html
https://cloud.tencent.com/developer/article/1543647
展示
5 真機(jī)調(diào)試
真機(jī)調(diào)試2.0支持canvas
解決問題
問題1 模型太大
只能放到線上,放到GitHub上,可以訪問raw.githubusercontent.com請求到資源
問題2 githubusercontent訪問不穩(wěn)定,經(jīng)常掛
放到碼云上,碼云同樣有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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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.

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

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.

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

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

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
