Adapter
The minigame runtime environment is JavaScriptCore on iOS and V8 on Android. Both are runtime environments without BOM or DOM, and without global document and window objects. Therefore, when you want to use DOM APIs to create elements such as Canvas and Image, errors will occur.
var canvas = document.createElement('canvas')However, we can use sud.createCanvas and sud.createImage to wrap a document.
var document = {
createElement: function (tagName) {
tagName = tagName.toLowerCase()
if (tagName === 'canvas') {
return sud.createCanvas()
}
else if (tagName === 'image') {
return sud.createImage()
}
}
}Now the code can create Canvas and Image just like creating elements in a browser.
var canvas = document.createElement('canvas')
var image = document.createImage('image')Similarly, if you want to create an Image object using new Image(), you only need to add the following code.
function Image () {
return sud.createImage()
}A library composed of such code that simulates BOM and DOM using OpenPaaS APIs is called an Adapter. As the name suggests, it is an adaptation layer for browser-based game engines under the minigame runtime environment, so that the game engine does not produce errors when calling DOM APIs and accessing DOM properties. An Adapter is an abstract code layer and does not refer to any specific third-party library that adapts minigames. Every developer can implement a corresponding Adapter according to their own project needs. Officially, an Adapter named weapp-adapter is provided, along with complete source code, for developers to use and reference.
weapp-adapter calls sud.createCanvas() in advance to create an on-screen Canvas and exposes it as a global variable Canvas.
require('./weapp-adapter')
var context = canvas.getContext('2d')
context.fillStyle = 'red'
context.fillRect(0, 0, 100, 100)In addition, weapp-adapter also simulates the following objects and methods:
- document.createElement
- canvas.addEventListener
- localStorage
- Audio
- Image
- WebSocket
- XMLHttpRequest
- and so on...
It should be emphasized that weapp-adapter's simulation of the browser environment is far from complete. It only simulates the properties and methods that game engines might access or call, and it does not guarantee that all game engines can be integrated seamlessly into minigames through weapp-adapter. Providing weapp-adapter directly to developers is mainly intended as a reference; developers can extend it based on weapp-adapter as needed to adapt to the game engine used by their own project.
