TikTok for Developers

Developer Docs

Last updated November 28, 2026

Integrate Your Web Game

Adapt the source project of an existing web game so it builds a package that runs in TikTok Mini Games.

Start from the engine or framework your game uses:

For example projects that show each type of adaptation, see Web Game Adaptation Examples. For account and app setup, see the Mini Games Quickstart. For API details, see the JavaScript SDK reference.

If your game is an HTML mini game that runs on the HTML runtime, see Migrate From HTML to Native Runtime.

Workflow diagram showing game adaptation from checking and adapting the game through platform features, build and debugging, to testing and release, with ongoing iteration

The adaptation follows four stages:

  1. Prepare a playable original and a working copy. Record the startup file, rendering method, assets, and build command.
  2. Adapt the first scene: the entry, renderer, touch input, and assets.
  3. Build the package and run it in the TikTok app with DevTool and a test account. Compare it with the original.
  4. Adapt the rest of the game, test on Android and iOS, then upload, preview, and submit.

The mini game runtime provides Canvas 2D and WebGL. You don't have to convert a WebGL game to HTML or Canvas 2D. The runtime has no DOM or CSS, so rebuild DOM and CSS interfaces as in-game UI.

Prerequisites

  • The source code, assets, and build instructions for your game, and a playable copy of the original
  • A mini game app on the Developer Portal. Record its client key, and register the HTTPS domains your game requests. For details, see Set Up Development Configuration.
  • A test account and DevTool. For setup steps, see the Mini Games Quickstart.

Check your existing game

Record the framework or engine version, dependencies, startup code, assets, and backend services. Choose a representative scene to adapt first.

A URL alone, or a built web game without its source, isn't enough to adapt. Get the source project first.

Identify how your game renders

Diagram comparing DOM, Canvas 2D, and WebGL game setups and whether to rebuild HTML UI or adapt browser APIs
  • Search the source for getContext('2d'), getContext('webgl'), and getContext('webgl2'). Inspect HTML files, CSS, and calls to document.
  • If your game uses a framework or engine, it might create the rendering context itself.
  • If your game uses Canvas 2D and WebGL together, find out what each is for: a visible layer, a texture source, or asset generation.
  • If your game uses WebGPU, check its rendering backend. Test any WebGL fallback in the mini game runtime.

A canvas element or a React wrapper doesn't mean the UI is HTML. A canvas game can still call document.

What your web game uses

What to adapt

DOM, CSS, and JavaScript

Rebuild the screens with Canvas 2D, WebGL, or your game's UI system.

Canvas 2D and JavaScript

Keep your drawing code. Create the canvas with the mini game API.

Canvas 2D and DOM

Follow the Canvas 2D path, and rebuild the DOM interfaces.

WebGL and JavaScript

Create the WebGL context on the mini game canvas, and adapt how shaders are loaded.

WebGL and DOM

Follow the WebGL path, and rebuild the DOM interfaces.

Check dependencies

Check each dependency your game uses against the mini game runtime:

  • Rendering: The Canvas API reference documents Canvas 2D and WebGL 1.0. The runtime also supports WebGL 2.
  • Browser integration: DOM, CSS, browser events, and browser storage need replacements.
  • WebAssembly: Check the loader, imports, memory settings, and any threading that depends on Workers.
  • Game services: Login, ads, purchases, and sharing must use the TikTok Mini Games APIs.

To find browser dependencies in a framework or custom engine, search the source for getContext, getElementById, querySelector, createElement, keydown, pointerdown, touchstart, fetch, XMLHttpRequest, DOMParser, XPath, AudioContext, localStorage, and visibilitychange.

If a dependency blocks your game, contact Developer Support with the dependency version, the API it calls, how your game uses it, and the error.

Adapt your game

Create the mini game entry

Flow diagram showing a game project adapted, built and packaged into Mini Game output with game.js, game.json, scripts and assets
  1. Find your game's browser entry, such as the HTML file and the script it starts.
  2. Separate the code that depends on the browser from your game code.
  3. Create the mini game entry. It initializes any adapter your game needs, gets the screen canvas and its context, and calls your game's startup function. Bundle it as game.js.
  4. Configure the build output:
    1. game.js: the startup entry.
    2. game.json: runtime configuration, such as {"deviceOrientation": "portrait"}.
    3. project.config.json: project configuration. Set appid to your client key.
    4. The assets the first scene needs. Add subpackages only when you need them.
  5. Run the build and inspect the output. This checks the package structure. It doesn't confirm that the game runs.

The following is an example project.config.json file:

{
  "projectname": "my-game",
  "appid": "CLIENT_KEY"
}

Replace CLIENT_KEY with your app's client key.

The following entry creates a WebGL context and starts the game:

import { startGame } from './game-source.js';

const canvas = TTMinis.game.createCanvas();
const gl = canvas.getContext('webgl');
if (!gl) throw new Error('WebGL context creation failed');
startGame({ canvas, gl });

Compile TypeScript and bundle your code into the package. Keep your changes in the source project or build scripts, not in the generated output. If your game uses a framework adapter, initialize it before the framework. A game that uses JavaScript directly doesn't need an engine directory or a browser emulation layer.

The following layout separates the source project from the generated package:

my-game/
├── src/                     # editable game and platform code
├── assets/                  # source assets
├── package.json             # your build scripts, if used
└── game/                    # generated package root for DevTool
    ├── game.js              # mini game startup entry
    ├── game.json            # runtime and subpackage configuration
    ├── project.config.json  # project configuration
    └── assets/              # packaged assets

Caution: A URL, an HTML ZIP file, or an unadapted browser build isn't a mini game package. DevTool runs the generated package directory.

Connect Canvas 2D or WebGL

The first call to createCanvas() returns the screen canvas. Later calls create off-screen canvases. If your adapter already creates the screen canvas, reuse it.

If your game draws on more than one canvas, compose the layers through the screen canvas. A Canvas 2D canvas can be the source of a WebGL texture. If your game renders in more than one pass or viewport, restore the WebGL state after each pass. For an example, see the Behind Asteroids setup code.

Initialize Canvas 2D:

const canvas = TTMinis.game.createCanvas();
const context = canvas.getContext('2d');
// Pass canvas and context to your existing 2D drawing code.

Initialize WebGL:

const canvas = TTMinis.game.createCanvas();
const gl = canvas.getContext('webgl');
if (!gl) throw new Error('WebGL context creation failed');
// Pass canvas and gl to your existing WebGL renderer.

For WebGL 2, pass 'webgl2' to getContext(). TTMinis.game is available without importing minis.js. The tt and wx prefixes are also compatible.

  • Canvas 2D: Load images with createImage(), and load the fonts your game draws with.
  • WebGL: Set the canvas backing size and the viewport to match the screen.

Move shaders out of HTML

If your shaders are embedded in HTML, move them into a JavaScript module, such as shaders.js:

const vertexSource = `#version 300 es
in vec2 a_position;
void main() {
  gl_Position = vec4(a_position, 0.0, 1.0);
}`;

module.exports = { vertexSource };

Then compile them from your renderer:

const { vertexSource } = require('./shaders');
const shader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(shader, vertexSource);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  throw new Error('Vertex shader compilation failed: ' + gl.getShaderInfoLog(shader));
}
// Attach this shader and your compiled fragment shader to your program.

PixiJS 8 generates shader code at runtime. Import its unsafe-eval module before you initialize the renderer. This was checked with PixiJS 8.16.0. For details, see the PixiJS environments guide.

import 'pixi.js/unsafe-eval';
// Initialize your PixiJS renderer after this import.

Connect an existing WebGL renderer

  1. Find where your renderer gets the canvas and calls getContext().
  2. Create the screen canvas with TTMinis.game.createCanvas() and pass it to the renderer.
  3. Set the canvas size and viewport. Initialize shaders, buffers, and textures, and load the first scene's assets.
  4. Build the package and run it on a phone. If the screen is blank, check the first error, the context creation, shader compilation, and asset paths.

Replace unsupported Canvas 2D methods

If a Canvas 2D method your game uses isn't available, draw the shape with supported path methods. For example, if ctx.roundRect is not a function appears after the menu, replace roundRect() with a helper:

function roundedRectPath(ctx, x, y, width, height, radius) {
  const r = Math.max(0, Math.min(radius, width / 2, height / 2));
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + width - r, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + r);
  ctx.lineTo(x + width, y + height - r);
  ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
  ctx.lineTo(x + r, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - r);
  ctx.lineTo(x, y + r);
  ctx.quadraticCurveTo(x, y, x + r, y);
  ctx.closePath();
}

ctx.beginPath();
roundedRectPath(ctx, 10, 10, 100, 20, 4);
ctx.fill();

Adapt input, audio, files, and saves

Browser feature

Mini game replacement

Mouse, pointer, and touch events

onTouchStart, onTouchMove, onTouchEnd, and onTouchCancel

HTML menus and dialogs

In-game UI, the UI APIs, and the safe area

Web Audio and HTML audio

The Audio APIs

fetch and XMLHttpRequest

The Network Request and File APIs. Register each HTTPS domain on the Developer Portal.

localStorage

The Data Storage APIs. Use a backend for progress across devices.

To keep players' progress when you move an existing HTML mini game, see Migrate From HTML to Native Runtime.

Map touch coordinates

Touch events report positions in window coordinates. If your game content is scaled or centered inside the window, convert each touch to game coordinates:

  1. Get the window size from the system info APIs.
  2. Calculate the scale and offset your renderer uses.
  3. Convert each touch position to game coordinates.
  4. Ignore touches outside the game area.

The following function converts a touch for content that is centered and uniformly scaled inside the window:

// For game content centered and uniformly scaled inside the window.
function toGamePoint(windowX, windowY, windowWidth, windowHeight, gameWidth, gameHeight) {
  const scale = Math.min(windowWidth / gameWidth, windowHeight / gameHeight);
  const offsetX = (windowWidth - gameWidth * scale) / 2;
  const offsetY = (windowHeight - gameHeight * scale) / 2;
  const x = (windowX - offsetX) / scale;
  const y = (windowY - offsetY) / scale;
  return { x, y, inside: x >= 0 && x < gameWidth && y >= 0 && y < gameHeight };
}

For example, toGamePoint(195, 422, 390, 844, 400, 700) returns { x: 200, y: 350, inside: true }. Don't multiply touch positions by the device pixel ratio.

Adapt audio

  • If your game synthesizes sound with Web Audio, export the sounds as audio files.
  • If your game uses an audio sprite, cut each sound into its own file:
ffmpeg -i assets/effects.mp3 -ss 5.2 -t 0.5 -vn assets/shot.mp3
  • If your game uses OGG files, convert them to MP3:
  • ffmpeg -i assets/shot.ogg -c:a libmp3lame -b:a 128k assets/shot.mp3

    Include the clips in the package. For each effect, create one audio context at startup, and call it from the game's existing action. For example, call playShot() from the shot action:

    const shot = tt.createInnerAudioContext();
    let shotReady = false;
    shot.onCanplay(() => { shotReady = true; });
    shot.onError(error => { shotReady = false; console.error('Shot audio:', error); });
    shot.src = 'assets/shot.mp3';
    
    function playShot() {
      if (!shotReady) return;
      shot.stop(); // Restart this effect if it is already playing.
      shot.play();
    }

    Destroy audio contexts when the scene that owns them is no longer needed. Keep the original volume, mute, and looping behavior, and keep the licenses for the audio and tools you use. On target phones, test repeated and overlapping sounds, and pausing and resuming. Splitting and re-encoding can change timing or sound.

    If audio plays in a browser but is silent on a phone, check the onError and onCanplay callbacks, the packaged file path, and the encoding.

    Adapt text input, saves, and visibility

    • Text input: Replace HTML input fields with showKeyboard(). The keyboard APIs require SDK 0.6.0 or later.
    • Saves: Write each save as a single complete record, so an interrupted write doesn't leave partial data.
    • Visibility: Use onHide to save state and pause audio and timers, and onShow to resume.

    Convert an XML texture atlas

    If your game loads an XML texture atlas and your loader expects JSON, convert the atlas at build time. The following convert_atlas.py script supports atlases without rotation or trimming:

    import json
    import xml.etree.ElementTree as ET
    
    source = 'spritesheet/sheet.xml'
    target = 'spritesheet/sheet.json'
    frames = {}
    required = {'name', 'x', 'y', 'width', 'height'}
    for item in ET.parse(source).getroot():
      if item.tag != 'SubTexture' or set(item.attrib) != required:
        raise ValueError('Use an exporter that preserves this atlas format')
      a = item.attrib
      if a['name'] in frames:
        raise ValueError('Duplicate frame: ' + a['name'])
      frames[a['name']] = {'frame': {
        'x': int(a['x']), 'y': int(a['y']),
        'w': int(a['width']), 'h': int(a['height'])
      }}
    if not frames:
      raise ValueError('Atlas contains no frames')
    with open(target, 'w', encoding='utf-8') as output:
      json.dump({'frames': frames}, output)

    Then load the JSON atlas. For example, in Phaser:

    this.load.atlas('sprites', 'spritesheet/sheet.png', 'spritesheet/sheet.json');

    Integrate platform features

    Call the platform APIs through TTMinis.game. For details, see the JavaScript SDK reference.

    Feature

    Connect it to the game

    Guide

    Home screen shortcut and sidebar revisit

    Integrate both before you submit your game. Add the in-game entry, and handle the return parameters. Keep the game playable when an entry isn't available. Rewards are optional. If you offer them, use the result of the client API and prevent duplicate grants.

    Home Screen Shortcut, Revisit From Profile

    Player identity and account saves

    Integrate login for in-app purchases or features tied to an account. Call TTMinis.game.login(), send its temporary code to your game server, and establish the game session there. Test server failures and session recovery.

    Login

    Profile data

    Request authorization when a feature needs the data. Check the required scope and app permissions, and handle refusal or failure. Silent login alone doesn't authorize access to profile data.

    Login

    Ads

    Turn on in-app ads, configure the ad unit, and connect the ad to the game action. For rewarded ads, grant the reward only after the player completes the ad. Handle incomplete views, unavailable ads, errors, and duplicate callbacks.

    In-App Ads

    Purchases

    Turn on in-app purchases and integrate login. Connect order creation on your server to the payment on the client, check the order status on your server, and deliver the item once. Handle cancelled and interrupted payments.

    In-App Purchases

    Sharing and invitations

    Connect the share button, configure the share card and query parameters, and restore the intended state when a recipient opens the game. Test sending and opening separately. A success callback alone doesn't confirm that the message was delivered or opened.

    Sharing

    Keep your client secret and the token exchange on your game server. Never include the client secret in the package. The login callback on the client provides a temporary code, and your server establishes the player's identity and game session.

    For purchases, check the order status before you deliver the item. For optional revisit rewards, follow the eligibility result from the client API and your game's reward rules.

    Complete the platform configuration before you test a feature that depends on it. Check each feature guide for app and region requirements.

    Use local simulation or the DevTool mocks to test UI and callback branches. Then turn off the mocks and test the real service on a phone with the TikTok app. Test real shortcut and sharing entries against the released version, as described in their guides.

    Build and debug

    Build the adapted package and open it in DevTool.

    If you need subpackages:

    1. Move content that isn't needed at startup into a subpackage directory.
    2. Declare the subpackage in game.json.
    3. Call loadSubpackage() before the game uses the content. To download a subpackage without running it, call preDownloadSubpackage().
    4. Rebuild and check the package size in DevTool.

    Moving files into subpackages doesn't reduce the total package size. You can host eligible assets remotely, but never download executable code. For details, see Manage Packages and Assets.

    To run the game, start DevTool from the package directory, select Client preview, and scan the QR code with your test account. Compare the game on the phone with the original.

    If the screen is blank, open vConsole on the phone and check the first error. Then check the canvas and context creation, shader compilation, and asset paths.

    Test and release

    1. Upload the package from DevTool to create a code version.
    2. Test the uploaded code version with Preview.
    3. Test performance on Android and iOS phones.
    4. Submit the game for review and release it.
    Diagram comparing Client preview via local code and DevTool with Platform Preview via uploaded package and platform version

    For details, see Release Your Mini Game.

    Troubleshooting

    Problem

    Check and resolve

    The screen is blank.

    Check the first error in vConsole, then check the canvas and context creation, shader compilation, and asset paths.

    An error says a method isn't a function.

    The runtime doesn't provide that browser or Canvas API. Replace the call with a supported API, as in the roundRect() example.

    Touches land in the wrong place.

    Convert touch positions to game coordinates. Don't multiply them by the device pixel ratio.

    A network request fails on the phone.

    Register the HTTPS domain on the Developer Portal.

    Audio doesn't play.

    Convert OGG files to MP3, and wait for onCanplay before the first play.

    Next steps

    TikTok for Developers