Learn how to develop WeChat games with pixi.js
Oct 29, 2020 pm 05:39 PMWeChat Mini Program Development column introduces how to use pixi.js to develop WeChat mini games.
1. Use PixiJS rendering engine
WeChat mini game is a JavaScript running environment different from the browser, without BOM and DOM API. However, pixi.js uses JavaScript combined with other HTML5 technologies to display media, create animations or manage interactive images. It relies on the BOM and DOM API provided by the browser. Therefore, if you want to use pixi.js in WeChat mini games, you need to modify the engine.
However, the mini game provides support for most Canvas 2d and WebGL 1.0 features. For support information, see RenderingContext. pixi.js can automatically detect whether WebGL or Canvas is used to create graphics.
No matter what kind of engine it is, most of what is ultimately done when the game is running is updating the screen and playing sounds with user interaction. The development language of mini games is JavaScript, so at the bottom level of the engine, the drawing API and audio API need to be called through JavaScript.
The API that a piece of JavaScript code can call during runtime depends on the host environment
. Our most commonly used console.log
is not even part of the core of the JavaScript language, but is provided by the browser hosting environment. Common hosting environments include browsers, Node.js, etc. Browsers have BOM and DOM APIs, but Node.js does not; Node.js has file and network APIs provided by Node.js core modules such as fs and net, but browsers do not have these modules. For example, the following code that runs normally in the browser will report an error when run in Node.js.
let?canvas?=?document.createElement('canvas')復制代碼
Because the Node.js host environment does not provide the built-in global variable document at all.
ReferenceError:?document?is?not?defined復制代碼
The running environment of the mini game is a host environment different from the browser. It does not provide BOM and DOM API, but wx API. Through the wx API, developers can call the drawing, audio and video, network, file and other capabilities provided by Native.
If you want to create a canvas, you need to call wx.createCanvas()
let?canvas?=?wx.createCanvas()let?context?=?canvas.getContext('2d')復制代碼
If you want to create an audio object, you need to call wx.createInnerAudioContext()
let?audio?=?wx.createInnerAudioContext()//?src?地址僅作演示,并不真實存在audio.src?=?'bgm.mp3'audio.play()復制代碼
If you want to get the width and height of the screen, you need to call wx.getSystemInfoSync()
let?{?screenWidth,?screenHeight?}?=?wx.getSystemInfoSync()復制代碼
But the rendering engine based on pixi.js will create the stage and mount it in the following way When you go to page
document.body.appendChild(app.view);復制代碼
, an error will occur. The reason is as mentioned above. The host environment of the mini game does not provide document and window, two global variables built into the browser. Because the mini game environment is a hosting environment different from the browser.
ReferenceError:?document?is?not?definedReferenceError:?window?is?not?defined復制代碼
Therefore, basically small games developed based on pixi.js cannot be directly migrated to small games for use, because the implementation of pixi.js may more or less use browsers such as BOM and DOM. Environment-specific APIs. Only by transforming pixi.js and changing the BOM and DOM API calls to wx API calls can it run in the mini-game environment.
But we cannot change the code of pixi.js, and there is no way to directly modify the API implementation. There is another adaptation method, which is to add a layer of simulated BOM and DOM between the rendering engine and the game logic code. The adaptation layer of the API is called Adapter. This adaptation layer globally simulates the properties and methods of the window and document objects that the engine will access through the wx API, so that the engine cannot feel the differences in the environment.
Adapter is user code and is not part of the base library. For an introduction to Adapter, see the tutorial Adapter.
2. Adapter Adapter
1. weapp-adapter
The running environment of the mini game is JavaScriptCore on iOS and V8 on Android, both of which have no BOM and DOM. The running environment does not have global document and window objects. Therefore, when you want to use the DOM API to create elements such as Canvas and Image, an error will occur.
const?canvas?=?document.createElement('canvas')復制代碼
But we can use wx.createCanvas and wx.createImage to encapsulate a document.
const?document?=?{????createElement:?function?(tagName)?{ ????????tagName?=?tagName.toLowerCase()????????if?(tagName?===?'canvas')?{????????????return?wx.createCanvas() ????????}????????else?if?(tagName?===?'image')?{????????????return?wx.createImage() ????????} ????} }復制代碼
At this point the code can create Canvas and Image just like creating elements in the browser.
const?canvas?=?document.createElement('canvas')const?image?=?document.createImage('image')復制代碼
Similarly, if you want to create an Image object using new Image(), just add the following code.
function?Image?()?{????return?wx.createImage() }復制代碼
這些使用 wx API 模擬 BOM 和 DOM 的代碼組成的庫稱之為 Adapter。顧名思義,這是對基于瀏覽器環(huán)境的游戲引擎在小游戲運行環(huán)境下的一層適配層,使游戲引擎在調用 DOM API 和訪問 DOM 屬性時不會產生錯誤。
Adapter 是一個抽象的代碼層,并不特指某一個適配小游戲的第三方庫,每位開發(fā)者都可以根據自己的項目需要實現相應的 Adapter。官方實現了一個 Adapter 名為 weapp-adapter, 并提供了完整的源碼,供開發(fā)者使用和參考。
**
Adapter 下載地址 weapp-adapter.zip
weapp-adapter 會預先調用 wx.createCanvas() 創(chuàng)建一個上屏 Canvas,并暴露為一個全局變量 canvas。
require('./weapp-adapter')var?context?=?canvas.getContext('2d') context.fillStyle?=?'red'context.fillRect(0,?0,?100,?100)復制代碼
除此之外 weapp-adapter 還模擬了以下對象和方法:
- document.createElement
- canvas.addEventListener
- localStorage
- Audio
- Image
- WebSocket
- XMLHttpRequest
- 等等...
需要強調的是,weapp-adapter 對瀏覽器環(huán)境的模擬是遠不完整的,僅僅只針對游戲引擎可能訪問的屬性和調用的方法進行了模擬,也不保證所有游戲引擎都能通過 weapp-adapter 順利無縫接入小游戲。直接將 weapp-adapter 提供給開發(fā)者,更多地是作為參考,開發(fā)者可以根據需要在 weapp-adapter 的基礎上進行擴展,以適配自己項目使用的游戲引擎。
2. pixi-adapter
小游戲基礎庫只提供 wx.createCanvas 和 wx.createImage 等 wx API 以及 setTimeout/setInterval/requestAnimationFrame 等常用的 JS 方法。
1.全局對象
window對象是瀏覽器環(huán)境下的全局對象。小游戲運行環(huán)境中沒有BOM API,因此沒有window對象。但是小游戲提供了全局對象GameGlobal,所有全局定義的變量都是GameGlobal的屬性。
console.log(GameGlobal.setTimeout?===?setTimeout);console.log(GameGlobal.requestAnimationFrame?===?requestAnimationFrame);復制代碼
以上代碼執(zhí)行結果均為true。 開發(fā)者可以根據需要把自己封裝的類和函數掛載到GameGlobal上。
GameGlobal.render?=?function(){????//?具體的方法實現} render();復制代碼
2. Element 元素構造
import?{?canvas?}?from?'./canvas'/** ?*?Base?Element ?*/export?class?Element?{ ??style?=?{?cursor:?null?}??appendChild()?{}??removeChild()?{}??addEventListener()?{}??removeEventListener()?{} }export?const?HTMLCanvasElement?=?canvas.constructorexport?const?HTMLImageElement?=?wx.createImage().constructorexport?class?HTMLVideoElement?extends?Element?{ }復制代碼
3. document 構造
import?{?Canvas?}?from?'./canvas'import?Image?from?'./Image'import?{?Element?}?from?'./element'const?stack?=?{}/**? ?*?document?適配 ?*/export?default?{??body:?new?Element('body'),??addEventListener(type,?handle)?{ ????stack[type]?=?stack[type]?||?[] ????stack[type].push(handle) ??},??removeEventListener(type,?handle)?{????if?(stack[type]?&&?stack[type].length)?{??????const?i?=?stack[type].indexOf(handle) ??????i?!==?-1?&&?stack[type].splice(i) ????} ??},??dispatch(ev)?{????const?queue?=?stack[ev.type] ????queue?&&?queue.forEach(handle?=>?handle(ev)) ??},??createElement(tag)?{????switch?(tag)?{??????case?'canvas':?{????????return?new?Canvas() ??????}??????case?'img':?{????????return?new?Image() ??????}??????default:?{????????return?new?Element() ??????} ????} ??} }復制代碼
4.統(tǒng)一入口
import?{?noop?}?from?'./util'import?Image?from?'./Image'import?{?canvas?}?from?'./canvas'import?location?from?'./location'import?document?from?'./document'import?WebSocket?from?'./WebSocket'import?navigator?from?'./navigator'import?TouchEvent?from?'./TouchEvent'import?XMLDocument?from?'./XMLDocument'import?localStorage?from?'./localStorage'import?XMLHttpRequest?from?'./XMLHttpRequest'import?{?Element,?HTMLCanvasElement,?HTMLImageElement,?HTMLVideoElement?}?from?'./element'const?{?platform?}?=?wx.getSystemInfoSync() GameGlobal.canvas?=?canvas?//?全局canvascanvas.addEventListener?=?document.addEventListener canvas.removeEventListener?=?document.removeEventListener//?模擬器?掛載window上不能修改if?(platform?===?'devtools')?{??Object.defineProperties(window,?{????Image:?{value:?Image},????Element:?{value:?Element},????ontouchstart:?{value:?noop},????WebSocket:?{value:?WebSocket},????addEventListener:?{value:?noop},????TouchEvent:?{value:?TouchEvent},????XMLDocument:?{value:?XMLDocument},????localStorage:?{value:?localStorage},????XMLHttpRequest:?{value:?XMLHttpRequest},????HTMLVideoElement:?{value:?HTMLVideoElement},????HTMLImageElement:?{value:?HTMLImageElement},????HTMLCanvasElement:?{value:?HTMLCanvasElement}, ??})??//?掛載?document ??for?(const?key?in?document)?{????const?desc?=?Object.getOwnPropertyDescriptor(window.document,?key)????if?(!desc?||?desc.configurable)?{??????Object.defineProperty(window.document,?key,?{value:?document[key]}) ????} ??} }?else?{ ??GameGlobal.Image?=?Image ??GameGlobal.window?=?GameGlobal ??GameGlobal.ontouchstart?=?noop ??GameGlobal.document?=?document ??GameGlobal.location?=?location ??GameGlobal.WebSocket?=?WebSocket ??GameGlobal.navigator?=?navigator ??GameGlobal.TouchEvent?=?TouchEvent ??GameGlobal.addEventListener?=?noop ??GameGlobal.XMLDocument?=?XMLDocument ??GameGlobal.removeEventListener?=?noop ??GameGlobal.localStorage?=?localStorage ??GameGlobal.XMLHttpRequest?=?XMLHttpRequest ??GameGlobal.HTMLImageElement?=?HTMLImageElement ??GameGlobal.HTMLVideoElement?=?HTMLVideoElement ??GameGlobal.HTMLCanvasElement?=?HTMLCanvasElement ??GameGlobal.WebGLRenderingContext?=?GameGlobal.WebGLRenderingContext?||?{} }復制代碼
思路建議為先引入通用的 Adapter 嘗試運行,然后遇到的問題再逐個解決掉。
相關免費學習推薦:微信小程序開發(fā)
The above is the detailed content of Learn how to develop WeChat games with pixi.js. 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)