PlayCanvas
Use ZokoGames in a PlayCanvas 2.x game through the integration script or the JavaScript SDK, with ad pausing, loading reports, banners, saves and local testing.
- Install
- A working game with the integration
- What the integration gives you
- In the PlayCanvas Editor
- Without the integration
- Banners
- Room data channel and purchases
- Export settings that matter on the web
- Chat reports, screenshots and storage mirror
- SDK 1.7.0 additions
- Test locally
- API
- init
- ad.*
- banner.*
- game.*
- user.*
- data.*
- store.*
- achievements.*
- analytics.*
- constants
- Known pitfalls
- Next
PlayCanvas games run in the browser, so you have two ways in. Use the ZokoGames PlayCanvas integration (packages/sdk-engines/playcanvas), which freezes the application and silences the sound manager around ads for you and ships ready-to-drop Editor scripts, or call the JavaScript SDK directly. Both use the same calls, limits and error codes. Jargon such as "midgame" and "rewarded" is explained in the glossary.
Plugin 1.7.2. Verified with PlayCanvas engine 2.24.2: strict type check, the example run in a headless browser, and the production check on all 12 areas with an engine-only build. Not run inside the PlayCanvas Editor, which needs an account. Send the PlayCanvas version and the exact error to support if something fails. Release 1.7.2 (script-load timeout) was re-run on 2026-11-23, in a browser and on production.
Install#
Download the PlayCanvas integration: /sdk-engines/zokogames-playcanvas-1.7.2.zip (the same files as the folder in the repository).
/sdk-engines/playcanvas.zip is always the latest version. Checksums: /sdk-engines/SHA256SUMS. Index of every engine package with its version, size and SHA-256: /sdk-engines/engines.json.
Pick the route that matches your game.
| You have | Do this |
|---|---|
| An engine-only project (npm, Vite, Rollup, esbuild) | Copy src/ into your project and call ZokoPlayCanvas.attach(app) (below), or skip the helper and use the plain SDK. |
| A project in the PlayCanvas Editor | Upload editor/zokogames.mjs (ESM script, recommended) or editor/zokogames-classic.js (classic script) as a script asset and add it to the Root entity. Use one of them, not both. |
The integration is plain TypeScript in packages/sdk-engines/playcanvas/src/: ZokoPlayCanvas.ts, ZokoClient.ts, ZokoAppHost.ts, ZokoAdFlow.ts, ZokoLoadingBridge.ts, types.ts, an index.ts that re-exports them (no engine import) and ZokoScript.ts, the only file that imports playcanvas. The peer dependency is playcanvas ^2.0.0. The two Editor files are generated from src/ by tools/build-editor.mjs, so they contain the same code in one file each.
You do not have to add a script tag: when window.ZokoGames is missing, the integration injects https://sdk.zokogames.com/zokogames-sdk-v1.js itself (pass loadScript: false to turn that off). A script tag in index.html is still better, because the upload validator looks for the SDK URL (see build validation):
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>A working game with the integration#
This is the structure of the package's examples/minimal game: init, a loading report, gameplay start, a rewarded ad, a save and a load. Every portal call is wrapped so the game also runs when the SDK is disabled (see local mode).
import * as pc from "playcanvas";
import { ZokoPlayCanvas } from "./zokogames-playcanvas";
const app = new pc.Application(document.getElementById("game") as HTMLCanvasElement);
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW);
const zoko = ZokoPlayCanvas.attach(app, { syncMute: true }); // one instance per app; also app.zoko
async function main() {
// ready() loads the script if missing, then runs SDK.init(). It rejects with { code: "sdkNotLoaded" } when the script cannot load.
await zoko.ready().catch((e) => console.warn("ZokoGames unavailable:", e.code));
const live = zoko.isAvailable; // false on a disabled host: skip every SDK call
const assets = [new pc.Asset("level", "json", { url: "assets/level.json" }) /* ... */];
assets.forEach((a) => app.assets.add(a));
if (live) zoko.trackAssets(assets); // loadingStart, loadingProgress per asset, loadingStop after the last
await new Promise<void>((done) => new pc.AssetListLoader(assets, app.assets).load(() => done()));
app.start();
// ... build the scene ...
let best = Number(live ? zoko.data.getItem("best") ?? "0" : "0") || 0; // load: synchronous
if (live) await zoko.game.gameplayStart(); // input is live now, not at page load
async function watchForBonus() { // call from a button press
const { finished, error } = await zoko.requestAd("rewarded"); // timeScale 0 and sound suspended meanwhile
if (!finished) { console.warn("no ad:", error?.code); return; } // adCooldown, unfilled, adblock ... the game just carries on
best += 10; // reward only after adFinished
if (live) zoko.data.setItem("best", String(best)); // batched; sent about a second later
}
}
void main();Call zoko.game.gameplayStop() when a round ends or the page is hidden, and gameplayStart() again when play resumes. A midgame ad is requested at a natural break, after gameplayStart has been called once: since SDK 1.6.4 the local mode refuses a midgame ad with adCooldown until then.
What the integration gives you#
| Member | Behaviour (verified in ZokoPlayCanvas.ts, ZokoAppHost.ts and ZokoAdFlow.ts) |
|---|---|
ZokoPlayCanvas.attach(app, config?) |
Creates the helper once per application and sets app.zoko; later calls return the same instance. Config: syncMute (default true), screenshots (true), loadScript (true), forwardAppEvents (true). |
ready() |
Loads the SDK script if window.ZokoGames is missing, then runs SDK.init(). Rejects with { code: "sdkNotLoaded" } when the script cannot load. Safe to call repeatedly. When the environment is not disabled it also registers the settings and offline listeners, applies muteAudio to the sound manager volume (option syncMute) and registers the screenshot provider (option screenshots). |
requestAd("midgame" | "rewarded") |
On adStarted it suspends the sound manager, sets its volume to 0 and sets app.timeScale to 0. On adFinished, on adError, and when the request itself throws, it restores the earlier timeScale, sets the volume to the portal's muteAudio (or what it was) and resumes the sound manager. Resolves { finished, error? } and never rejects for ad problems. |
isAdPlaying, isAvailable, version |
true while an ad is on screen; true when ready and the SDK is not disabled; the JavaScript SDK release the integration was written against (SDK_VERSION). |
events |
Emits adStarted, adFinished, adError(error), settingsChange(settings) and offlineChange(offline). Each is also fired on the application as zoko:<name> (for example app.on("zoko:adStarted", ...)). |
sdk, client |
The raw SDK (throws sdkNotInitialized before ready() resolved) and the typed ZokoClient. |
ad, banner, game, user, data, store, achievements, analytics, environment, isQaTool |
The typed client, with the same module names as the JS SDK (zoko.game.gameplayStart(); app.game does not exist in PlayCanvas, so there is no clash). |
trackAssets(assets) |
Reports a list of assets (the list you give a pc.AssetListLoader) to the portal: loadingStart, loadingProgress (0 to 100) after each asset that loads or fails, loadingStop after the last. Assets already loaded count as done. Returns a function that detaches the listeners. |
trackPreload() |
Reports the application's own preload:start, preload:progress and preload:end. An Editor build runs its preload before any script, so it only helps when you attach earlier than that. |
requestBannerAt(id, x, y, w, h, size?) |
Positions a DOM container over a rectangle in canvas pixels (the graphics device's width and height) and requests a banner there; without size it requests the largest responsive size that fits. rectFromCanvasPixels gives the normalised rectangle. |
useDefaultScreenshot() |
Answers the portal's feedback form with the application's canvas as it stands at the end of the next rendered frame, as a JPEG. Registered by ready() unless screenshots: false; resolves no picture when no frame is rendered within a second. |
dispose() |
Detaches every listener, restores loop and sound and forgets the application. |
runAdFlow, createAppAdHost, bindPreloadProgress and bindAssetProgress are exported for custom setups, and ZokoClient can be used on its own in unit tests (it needs no PlayCanvas).
Setting timeScale to 0 freezes everything that scales with the engine's delta time: scripts that use dt, tweens, animation, physics. Rendering keeps running. Anything that reads the wall clock (Date.now(), setTimeout, CSS animations) does not stop, so pause those yourself on adStarted. A second requestAd while one is running resolves at once with error other. A timeScale or volume your game sets during an ad is kept.
In the PlayCanvas Editor#
Upload editor/zokogames.mjs as a script asset (run Parse if the Editor does not list the script), add the script zokoGames to the Root entity, and launch. The script has four attributes: syncMute, screenshots, loadScript and autoLoadingStop (call loadingStop as soon as the SDK is ready, default on). It attaches the helper (app.zoko), starts ready() and fires zoko:ready (with the helper) or zoko:error (with { code, message }) on the script and on the application. editor/zokogames-classic.js does the same as a classic script (pc.createScript("zokoGames")) in a classic project.
From your own script:
export class Game extends Script {
static scriptName = "game";
async initialize() {
const zoko = await this.app.root.script.zokoGames.ready; // the helper, or null when the SDK is unavailable
if (!zoko || !zoko.isAvailable) return;
await zoko.game.gameplayStart();
this.app.on("zoko:settingsChange", (s) => console.log("muted:", s.muteAudio));
}
}Add the SDK script tag to the project's index.html as shown above if you use a custom one. The Editor's own loading screen runs before the scripts, so the portal's loading bar is closed by autoLoadingStop rather than driven by it; for assets you load later, call zoko.trackAssets(...).
Without the integration#
If you do not want a helper, call the SDK yourself. Initialise before you start the application, and write the ad helper so it resumes on both outcomes.
const SDK = window.ZokoGames?.SDK;
let live = false;
async function main() {
if (SDK) { await SDK.init(); live = SDK.environment !== "disabled"; } // init never rejects
app.start();
if (live) {
const apply = (s) => { app.soundManager.volume = s.muteAudio ? 0 : 1; };
apply(SDK.game.settings);
SDK.game.addSettingsChangeListener(apply);
}
}
function showAd(app, type) {
if (!live) return Promise.resolve(false);
let paused = false;
let scale = 1;
const pause = () => { if (paused) return; paused = true; scale = app.timeScale; app.timeScale = 0; app.soundManager.suspend(); app.soundManager.volume = 0; };
const resume = () => {
if (!paused) return; paused = false;
app.timeScale = scale;
app.soundManager.volume = SDK.game.settings.muteAudio ? 0 : 1;
app.soundManager.resume();
};
return new Promise((done) => {
SDK.ad.requestAd(type, {
adStarted: pause,
adFinished: () => { resume(); done(true); },
adError: () => { resume(); done(false); },
}).catch(() => { resume(); done(false); }); // throws (for example sdkDisabled) instead of calling adError
});
}
main();requestAd resolves only after adFinished or adError has been delivered, so await showAd(...) is a safe place to resume game logic. On PlayCanvas builds before the application had app.soundManager, the manager is app.systems.sound.manager.
Kids mode. SDK.game.settings.kidsMode is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring disableChat, which the portal sets to true in the same cases. To test it, add ?kidsMode=true to the page address in local mode. See kids mode.
Banners#
Banner containers are DOM elements next to the canvas, not entities. Request them on menu screens only and clear them before play.
<canvas id="game"></canvas>
<div id="menu-banner" style="width:728px;height:90px;margin:8px auto"></div>SDK.banner.requestBanner({ id: "menu-banner", width: 728, height: 90 }).catch(() => {});
// leaving the menu:
SDK.banner.clearAllBanners();With the integration, await zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250") creates the container for you over that rectangle of the canvas. Banners are refused while a video ad plays (videoAdPlaying) and a container can refresh only every 30 seconds (bannerCooldown).
Room data channel and purchases#
Both are the SDK's own and are reached through the typed client, with no PlayCanvas-specific code: zoko.game.room (messages between the players of a room and a host-written shared state; undefined on an SDK older than 1.3.0; see the game module and the multiplayer guide) and zoko.store (isAvailable, getCatalogItems, buyItem, getPurchaseToken; see in-game purchases). Check zoko.store.isAvailable before showing any purchase UI and verify ownership on your server. On localhost the SDK's local mode serves a test store and makes two browser tabs in the same room id behave like two players.
if (zoko.store.isAvailable) {
try {
const items = await zoko.store.getCatalogItems({ limit: 20 });
await zoko.store.buyItem(items[0].sku);
const token = await zoko.store.getPurchaseToken(); // send to your server and verify there
} catch (e) {
if ((e as { code?: string }).code === "purchaseCancelled") return;
}
}Export settings that matter on the web#
- Relative paths. Bundle with relative paths (Vite
base: "./"). Root-absolute paths (starting with a slash) break under the game's own origin and raise theabsolute_pathwarning. See technical requirements. A PlayCanvas Editor web build already uses relative paths. - Do not pre-compress. PlayCanvas asks for plain file names. A file ending in
.bror.gzis served withContent-Encoding, but your page would still request the plain name, so ship plain files. Keep the files small: the initial-download estimate uses uncompressed sizes. - Size. Compress textures (Basis or KTX2), keep audio at modest bitrates and load later levels after the first scene. The upload limits are 1,500 files, 250 MB unpacked and about 50 MB initial download (20 MB for mobile); see first frame fast.
- Canvas sizing. The frame size changes with fullscreen and rotation. Use
FILLMODE_FILL_WINDOW(orKEEP_ASPECT) and handleresize, so the game stays legible at every required resolution. - Audio unlock. Browsers block sound until the first pointer or key event; the sound manager resumes its context on the first interaction. Start music from a button press, not unconditionally at startup. Ads and
syncMutedo not replace this. - Fullscreen. Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame, including the portal's controls. Do not add a competing button.
- Memory. There is no threading or
SharedArrayBufferin the portal frame (the portal does not send cross-origin isolation headers).
After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.
Chat reports, screenshots and storage mirror#
zoko.game.reportChat(report), zoko.game.onScreenshotRequest(handler) and zoko.data.mirrorLocalStorage({ prefix: "save_" }). ready() registers the default screenshot provider (the canvas at the end of the next frame); pass screenshots: false to attach to skip it, or register your own handler when your game draws into another canvas. The mirror only covers localStorage.
SDK 1.7.0 additions#
zoko.analytics.track(name, params?) records a custom event (fire-and-forget; an invalid call is dropped by the SDK). zoko.game.room.addLeftListener(cb) receives { reason, roomId? } when the portal ends the player's room membership (reason is left, kicked, closed or disconnected) and returns a function that removes the listener; removeLeftListener(cb) does the same. data.mirrorIndexedDB is not bound yet: it has to run before the engine starts, so call it from your own page script. The { portalOnly: true } option of showInviteButton / hideInviteButton is reachable through zoko.sdk.game.
Test locally#
PlayCanvas always runs in a browser, so there is no editor simulator. Serve the game from localhost and the SDK starts in its own local mode: a three-second overlay stands in for each ad, banners are dashed boxes, two fake players exist, and cloud saves go to localStorage. Two things trip people up:
- A second midgame request within three minutes of the last ad fails with
adCooldown, and since SDK 1.6.4 the first one fails the same way until the game has calledgameplayStart. That is the real rule, so your game must handle it. submitScoreis accepted and does nothing visible in local mode, and the local token is unsigned.
Add ?sdk_debug=true to log every call, ?ad_response=unfilled to force ad failure, and ?user_response=logged_out to test the guest path. Then open the Preview tool, enter your local address and watch the requirements checklist tick.
API#
init#
| JavaScript | PlayCanvas |
|---|---|
init |
await zoko.ready() |
environment |
zoko.environment |
isQaTool |
zoko.isQaTool |
ad.*#
| JavaScript | PlayCanvas |
|---|---|
ad.requestAd |
zoko.requestAd(type) (pausing) or zoko.ad.requestAd(type, callbacks) |
ad.requestAd.adStarted |
callbacks.adStarted of zoko.ad.requestAd(type, callbacks); zoko.requestAd(type) pauses for you |
ad.requestAd.adFinished |
callbacks.adFinished; requestAd resolves { finished: true } |
ad.requestAd.adError |
callbacks.adError(error); requestAd resolves { finished: false, error } |
ad.hasAdblock |
zoko.ad.hasAdblock() |
banner.*#
| JavaScript | PlayCanvas |
|---|---|
banner.requestBanner |
zoko.banner.requestBanner({ id, width, height }) |
banner.requestResponsiveBanner |
zoko.banner.requestResponsiveBanner() |
banner.clearBanner |
zoko.banner.clearBanner() |
banner.clearAllBanners |
zoko.banner.clearAllBanners() |
game.*#
| JavaScript | PlayCanvas |
|---|---|
game.settings |
zoko.game.settings |
game.addSettingsChangeListener |
zoko.game.addSettingsChangeListener(fn) / zoko.events.on("settingsChange", fn) or app.on("zoko:settingsChange", fn) |
game.removeSettingsChangeListener |
zoko.game.removeSettingsChangeListener() |
game.gameplayStart |
zoko.game.gameplayStart() |
game.gameplayStop |
zoko.game.gameplayStop() |
game.loadingStart |
zoko.game.loadingStart() |
game.loadingStop |
zoko.game.loadingStop() |
game.loadingProgress |
zoko.game.loadingProgress(percentage) |
game.happytime |
zoko.game.happytime() |
game.reportGameCompletedPercentage |
zoko.game.reportGameCompletedPercentage() |
game.reportChat |
zoko.game.reportChat(report) |
game.onScreenshotRequest |
zoko.game.onScreenshotRequest(handler) / zoko.useDefaultScreenshot() |
game.setGameContext |
zoko.game.setGameContext() |
game.clearGameContext |
zoko.game.clearGameContext() |
game.isInstantMultiplayer |
zoko.game.isInstantMultiplayer |
game.isInstantJoin |
zoko.game.isInstantJoin |
game.isOffline |
zoko.game.isOffline |
game.addOfflineListener |
zoko.game.addOfflineListener(fn) / zoko.events.on("offlineChange", fn) or app.on("zoko:offlineChange", fn) |
game.removeOfflineListener |
zoko.game.removeOfflineListener(fn) |
game.updateRoom |
zoko.game.updateRoom() |
game.leftRoom |
zoko.game.leftRoom() |
game.addJoinRoomListener |
zoko.game.addJoinRoomListener() |
game.removeJoinRoomListener |
zoko.game.removeJoinRoomListener() |
game.inviteParams |
zoko.game.inviteParams |
game.inviteLink |
zoko.game.inviteLink() |
game.getInviteParam |
zoko.game.getInviteParam() |
game.showInviteButton |
zoko.game.showInviteButton(params) |
game.hideInviteButton |
zoko.game.hideInviteButton() |
game.room |
zoko.game.room |
game.room.send |
zoko.game.room.send(data, { to }) |
game.room.onMessage |
zoko.game.room.onMessage(cb) |
game.room.addMessageListener |
zoko.game.room.addMessageListener(cb) |
game.room.removeMessageListener |
zoko.game.room.removeMessageListener(cb) |
game.room.setState |
zoko.game.room.setState(patch) |
game.room.getState |
zoko.game.room.getState() |
game.room.onState |
zoko.game.room.onState(cb) |
game.room.addStateListener |
zoko.game.room.addStateListener(cb) |
game.room.removeStateListener |
zoko.game.room.removeStateListener(cb) |
game.room.members |
zoko.game.room.members() |
game.room.onMembers |
zoko.game.room.onMembers(cb) |
game.room.addMembersListener |
zoko.game.room.addMembersListener(cb) |
game.room.removeMembersListener |
zoko.game.room.removeMembersListener(cb) |
game.room.isHost |
zoko.game.room.isHost() |
game.room.onHostChange |
zoko.game.room.onHostChange(cb) |
game.room.addHostChangeListener |
zoko.game.room.addHostChangeListener(cb) |
game.room.removeHostChangeListener |
zoko.game.room.removeHostChangeListener(cb) |
game.room.selfId |
zoko.game.room.selfId |
game.room.onError |
zoko.game.room.onError(cb) |
game.room.addLeftListener |
zoko.game.room.addLeftListener(cb) |
game.room.removeLeftListener |
zoko.game.room.removeLeftListener(cb) |
game.room.addErrorListener |
zoko.game.room.addErrorListener(cb) |
game.room.removeErrorListener |
zoko.game.room.removeErrorListener(cb) |
user.*#
| JavaScript | PlayCanvas |
|---|---|
user.isUserAccountAvailable |
zoko.user.isUserAccountAvailable |
user.systemInfo |
zoko.user.systemInfo |
user.getUser |
zoko.user.getUser() |
user.listFriends |
zoko.user.listFriends() |
user.getUserToken |
zoko.user.getUserToken() |
user.showAuthPrompt |
zoko.user.showAuthPrompt() |
user.addAuthListener |
zoko.user.addAuthListener() |
user.removeAuthListener |
zoko.user.removeAuthListener() |
user.showAccountLinkPrompt |
zoko.user.showAccountLinkPrompt() |
user.submitScore |
zoko.user.submitScore() |
user.getXsollaUserToken |
zoko.user.getXsollaUserToken() |
data.*#
| JavaScript | PlayCanvas |
|---|---|
data.getItem |
zoko.data.getItem(key) |
data.setItem |
zoko.data.setItem(key, value) |
data.removeItem |
zoko.data.removeItem() |
data.clear |
zoko.data.clear() |
data.mirrorLocalStorage |
zoko.data.mirrorLocalStorage(options) |
store.*#
| JavaScript | PlayCanvas |
|---|---|
store.isAvailable |
zoko.store.isAvailable |
store.getCatalogItems |
zoko.store.getCatalogItems({ limit, offset }) |
store.getPlayerInventory |
zoko.store.getPlayerInventory({ limit, offset }) |
store.buyItem |
zoko.store.buyItem(itemId) |
store.consumeItem |
zoko.store.consumeItem() |
store.getPurchaseToken |
zoko.store.getPurchaseToken() |
store.setSandbox |
zoko.store.setSandbox() |
achievements.*#
| JavaScript | PlayCanvas |
|---|---|
achievements.list |
zoko.achievements.list() |
achievements.unlock |
zoko.achievements.unlock(key) |
achievements.onUnlock |
zoko.achievements.onUnlock(fn) |
analytics.*#
| JavaScript | PlayCanvas |
|---|---|
analytics.track |
zoko.analytics.track(name, params) |
analytics.trackOrder |
zoko.analytics.trackOrder() |
constants#
| JavaScript | PlayCanvas |
|---|---|
ERROR_CODES |
ZOKO_ERROR_CODES.<module> |
SDK_VERSION |
zoko.version |
Known pitfalls#
trackAssetsbeforeready(). The loading calls fail withsdkNotInitialized(a rejected promise, swallowed by the bridge) and nothing is reported. Awaitzoko.ready()first, then calltrackAssets.sdkNotLoaded. The script was blocked or offline andloadScriptis off or failed. Your game should still start;ready()rejecting is not fatal.- Calls on a disabled SDK throw
sdkDisabled. Checkzoko.isAvailablefirst, as above, or an unhandled rejection reaches your console. - Sound stays muted after an ad. Something else changed the sound manager volume during the ad. The integration restores the portal's
muteAudiovalue, or the volume it saw atadStarted; a volume your game set during the ad is kept. - Things move during an ad. They ignore
dt(wall-clock timers, CSS animations).app.timeScaleonly scales the engine's own update. - Banner in the wrong place.
requestBannerAtconverts canvas pixels using the graphics device size; check your canvas fill mode and resolution. - Two Editor scripts. Use either
zokogames.mjsorzokogames-classic.js, not both; the second attaches to the instance the first created. - Reward granted twice. Grant on
finished === trueonly, never on the button press.
Next#
- Plain JavaScript with another renderer: Plain HTML5, Three.js and PixiJS.
- All engines at a glance: engines overview.
- Upload: zip the build output with
index.htmlat the archive root, then follow the submission walkthrough.