Repository navigation
WeChat Mini Games
WeChat Mini Games (小游戏) are games played inside the WeChat app. They don't run in a browser: WeChat gives the game a canvas and its own wx API, and an adapter adds the browser objects a game expects.
This guide covers melonJS 20.15 or later: it fixes a regression that stopped recent versions running on WeChat (see Known issues). See Platforms for the other platforms.
Status: this page was checked against WeChat's documentation, its API typings and the adapter's source, and melonJS was run against that adapter in a simulation of WeChat's runtime. It hasn't been run in WeChat itself yet: if you ship a game there, please tell us how it went.
WeChat's adapter, weapp-adapter, adds what a web game expects: a document, Image (from wx.createImage()), Audio (from wx.createInnerAudioContext()), localStorage (WeChat's storage), touch events, and a global canvas, the one drawn on screen. Get it from WeChat's adapter guide, or take the copy in WeChat's minigame-demo (miniprogram/js/libs/weapp-adapter.js).
It must run before melonJS, which reads those objects as it loads.
├── game.js the entry point, which WeChat runs
├── game.json the configuration
├── js/
│ ├── weapp-adapter.js
│ └── game.bundle.js your game and melonJS, in one script
└── data/ the assets
game.json:
{
"deviceOrientation": "portrait"
}game.js loads the adapter, then the game:
require("./js/weapp-adapter.js");
require("./js/game.bundle.js");WeChat loads scripts with require(), not as ES modules, so bundle the game and melonJS into one script, for example with esbuild:
npx esbuild src/main.js --bundle --format=iife --outfile=wechat/js/game.bundle.jsA bundle in that form can't use await at its top level: start the game from an async function, as below.
import "./wx-fetch.js"; // see "Loading files"
import { Application, event, loader, state, video } from "melonjs";
async function start() {
const app = new Application(360, 640, {
canvas: GameGlobal.canvas, // the adapter's on-screen canvas
renderer: video.AUTO, // WebGL 2 where WeChat has it, otherwise Canvas
scale: "auto",
scaleMethod: "flex-height", // see "The screen size"
});
await app.init();
// pause when the player leaves WeChat, resume when they come back
wx.onHide(() => event.emit(event.BLUR));
wx.onShow(() => event.emit(event.FOCUS));
await loader.preload(resources);
state.set(state.PLAY, new PlayScreen());
state.change(state.PLAY);
}
start();WeChat always stretches its canvas over the whole screen, so the canvas needs the screen's shape. Use a scaleMethod that adapts the game's size to the screen:
-
"flex-height": a fixed width and the height of the screen, for a portrait game -
"flex-width": a fixed height and the width of the screen, for a landscape game -
"flex","fill-min"or"fill-max"
"fit" and "stretch" keep the game's own shape, which WeChat then distorts, and touches no longer land where the player taps.
WeChat scales the canvas up to the screen's pixels, so the game's size is its sharpness: a phone is often 1080 pixels wide or more, and a 360-wide game is drawn 3 times larger.
melonJS's loader reads JSON, Tiled maps, text and binary files with fetch, which WeChat doesn't have. Images don't need it: melonJS loads them through the adapter's Image. This fetch reads the files packaged with the game, which is all the loader asks of it:
// wx-fetch.js
const files = wx.getFileSystemManager();
const read = (filePath, encoding) =>
new Promise((resolve, reject) => {
files.readFile({
filePath,
encoding,
success: (result) => resolve(result.data),
fail: (result) => reject(new Error(result.errMsg)),
});
});
GameGlobal.fetch = async (url) => {
const path = url.split("?")[0];
try {
files.accessSync(path);
} catch {
return { ok: false, status: 404, statusText: "Not Found" };
}
return {
ok: true,
status: 200,
statusText: "OK",
text: () => read(path, "utf8"),
json: async () => JSON.parse(await read(path, "utf8")),
arrayBuffer: () => read(path),
};
};What WeChat expects of the files:
-
Paths start from the game's root folder:
data/img/player.png. A path starting with./isn't found. -
File types: WeChat only packages some of them, and
.tmj,.tmxand.tsxaren't among them. Save Tiled maps as JSON under a.jsonname, with their tilesets embedded. XML maps wouldn't load anyway: WeChat has noDOMParser. -
Size: 4 MB for the main package, 30 MB in all with subpackages. Larger assets go on a server, which must be an HTTPS domain listed in the game's settings, and are downloaded with
wx.downloadFile(); thefetchabove only reads the package.
save works as it is: the adapter's localStorage is WeChat's storage (wx.setStorageSync()), which holds up to 1 MB per key and 10 MB in all.
WeChat says when the player leaves and comes back with wx.onHide() and wx.onShow(). Nothing reports the browser's blur or visibility events there, so the game doesn't pause by itself: emit event.BLUR and event.FOCUS from them, as above. The application's pauseOnBlur, stopOnBlur and resumeOnFocus then decide what the game does (see Platforms).
WeChat has no AudioContext, so melonJS plays sound through the adapter's Audio, WeChat's InnerAudioContext: sound files play, with volume, looping and muting. What needs Web Audio isn't available: audio.tone(), audio.noise(), the effects (reverb, echo, filters) and 3D sound.
iPhones don't play Ogg files: use MP3, with audio.init("mp3").
Touches reach melonJS as pointer events, through the adapter. There is no mouse or keyboard.
A fontface asset needs FontFace, which WeChat doesn't have. Load a TTF file with wx.loadFont(), which returns its family name, and use that name in a Text; or draw text with BitmapText.
- Tiled maps in XML (no
DOMParser), and thevideoandscriptasset types. - WebGPU: WeChat only has it on Android, through its own
wx.getGPU().
| Symptom | Cause |
|---|---|
| images fail to load, "createImageBitmap is not a function" | melonJS before 20.15 |
the renderer is Canvas although WebGL works, or video.WEBGL throws "a WebGL 2 context could not be created" |
melonJS before 20.15 looked for a global WebGL2RenderingContext, which WeChat doesn't have |
| "HTMLAudioElement is not defined" when the game pauses or mutes | melonJS before 20.15 |
| JSON files and maps fail, "fetch is not defined" | WeChat has no fetch: add the one in Loading files
|
| a file is not found | its path starts with ./, or WeChat didn't package its type (.tmj): rename Tiled maps to .json
|
| the picture is distorted, and touches land beside the finger |
"fit" or "stretch": use a "flex" or "fill" scale method |
| the game keeps running when the player leaves WeChat | nothing emits event.BLUR: listen to wx.onHide() and wx.onShow()
|
- WeChat's mini-game guide and its adapter guide
-
minigame-api-typings: WeChat's own TypeScript definitions of the
wxAPI - Platforms
Thanks to qichunren, a web developer from Shanghai, for their help identifying and fixing the first issues between melonJS and WeChat.