banner
raye~

Raye's Journey

且趁闲身未老,尽放我、些子疏狂。
medium
tg_channel
telegram
twitter
douban
github
email
nintendo switch
playstation
steam_profiles
zhihu

Developing WeChat Mini Games with pixi.js - Solving a Problem

biaoti11

Developing WeChat Mini Games with pixi.js#

The version of pixi.js I am using is 5.2.1. The API for loading resources has changed to a global singleton object called PIXI.Loader.shared.

When running a WeChat Mini Game project, the code for loading image resources is written like this:

let loader = PIXI.Loader.shared
loader.add('bg', 'static/textures/bg.png');

However, the WeChat Developer Tools kept throwing an error, indicating that the indexOf method was missing. So I started tracing the error message and found that there was an if statement before calling the crossOrigin method.

The if statement checks the type of the source, and if it is not inherited from HTMLImageElement, it treats the source as a string and proceeds to the subsequent methods, resulting in an error when calling the indexOf method.

But the problem lies in the fact that the source is already an image object, so it naturally does not have the indexOf method, causing the error.

Untitled

So why did the instanceof check fail? I decided to test it in a browser environment.

Untitled 1

As you can see, it returns true.

Untitled 2

But why does it return false in the WeChat Mini Game environment? It's probably due to the adapter.

The adapter I'm using is a modified version of @iro/wechat-adapter (the original version provided by WeChat has many issues). I found a problematic code in the following section:

export class HTMLImageElement extends wx.createImage().constructor {

}

After testing, I found that wx.createImage().constructor is already HTMLImageElement itself. Adding extends here adds an extra layer to the prototype chain, causing issues.

For those who are not familiar with the prototype chain, you can take a look at this diagram to understand it briefly (in my understanding, instanceof and extends are essentially about searching the prototype chain).

Untitled 3

So we can simply change it to an assignment, without the need for extends.

export const HTMLImageElement = wx.createImage().constructor

If you only want to temporarily modify the code, you can clone the repository to your local machine, make the necessary changes, and then specify the local path in the project's dependencies:

"@iro/wechat-adapter": "file:/Users/rayepeng/Documents/OpenSource/MyFrontEndCode/wechat-adapter/src/",

This way, the project will run successfully.

PS. The modified wechat-adapter package has been published: https://www.npmjs.com/package/@rayepeng/wechat-adapter

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.