Home › Touch Controls for HTML5 Games: Virtual Joystick and Mobile Rules (2026)

Touch Controls for HTML5 Games: Virtual Joystick and Mobile Rules (2026)

Poki says a big share of its game plays happen on mobile, and it requires phone and tablet support. Touch is where browser games feel broken fastest: the page scrolls when the player drags, a double-tap zooms in, a long press selects the whole game, and the jump button stops working while the thumb is on the joystick. This guide fixes each of those with Pointer Events and a few lines of CSS, gives you a virtual joystick you can paste or hand to your coding agent, and lists what Poki, CrazyGames, Phaser and Godot expect. Every fact comes from MDN, the W3C, the portals' developer docs or the engines' own docs.

Last updated:

Free download · one page + PDF · updated weekly, current edition November 16, 2026

🎁 Free: The AI Game Dev Stack 2026

The best AI tool for each job in a solo or indie game (3D, sprites and pixel art, animation, audio, NPCs), MCP setups for Unity, Unreal, Godot and Roblox, and which free plans you can actually ship with.

Yours free when you join the VibeStack Weekly: new AI game-dev tools and releases every Monday, 5-minute read. Unsubscribe anytime.

Quick answers

QuestionShort answer
Touch events or Pointer Events?Pointer Events: one model for mouse, pen and touch, with an id per finger. Supported since Chrome 55, Firefox 59 and Safari 13 (iOS 13)
The page scrolls or zooms while I playtouch-action: none on the game element, set inside the game's own page: it doesn't reach into iframes
Joystick and jump at the same timeTrack each pointerId separately. Phaser only enables one touch pointer by default
The stick stops when my thumb slides off itPointer capture. Touchscreens capture the pointer implicitly; call setPointerCapture() anyway so the mouse behaves the same
Fullscreen on iPhone?No. Safari on iOS only supports element fullscreen on iPad, and CrazyGames forbids custom fullscreen buttons
Lock to landscape?screen.orientation.lock() works in Chrome on Android and Firefox 144+, usually only in fullscreen; not in Safari. Support both orientations or show a rotate prompt
Notches and rounded cornersviewport-fit=cover plus env(safe-area-inset-*) padding around your UI
How big should buttons be?WCAG's minimum is 24×24 CSS pixels (AA) and its enhanced level is 44×44 (AAA). For thumbs, start well above 44

This page is about touch input on phones and tablets. For zips, portals and SDKs see how to publish an HTML5 game; for controllers see Gamepad API controller support; Godot users should also read Godot web export for itch.io and Poki.

Use Pointer Events, not mouse plus touch

MDN describes Pointer Events as one event model for mouse, pen and touch, so a single set of handlers covers desktop and mobile. What matters for games:

Stop scrolling, zooming, long-press and selection

ProblemFixWhy it works
Dragging scrolls the page or panstouch-action: none on the game elementMDN: the browser uses touch-action to decide whether to pan or zoom, then fires pointercancel instead of your moves. none turns those gestures off; the most common use is a map or game surface
Double-tap zooms intouch-action: none (or manipulation on menus)manipulation keeps panning and pinch zoom but turns off double-tap zoom
Game runs in a portal's iframeSet touch-action inside your game's own pageThe W3C spec says touch-action doesn't cascade into embedded browsing contexts, so the portal's CSS can't fix it for you. Poki asks you to stop game scrolling from moving the parent page
Long press selects everything or opens the magnifieruser-select: none and -webkit-user-select: noneCrazyGames' technical requirements give this CSS for double-tap and press-and-hold on tablets. MDN's compat data shows Safari still needs the -webkit- prefix
iOS callout on long press-webkit-touch-callout: noneNon-standard and iOS Safari only, per MDN
Context menucontextmenu listener with preventDefault()MDN: contextmenu can be canceled (Firefox lets Shift+right-click through)
Pull-to-refresh, scroll chainingoverscroll-behavior: none on html, bodyMDN says it stops scroll chaining and pull-to-refresh; compat data still marks Safari's support as partial, so touch-action does the heavy lifting
preventDefault() ignored in touch handlersPass { passive: false }, or use Pointer Events plus touch-actionMDN: touchstart and touchmove listeners on window, document and body default to passive, which can't cancel scrolling

Two more rules from the specs. touch-action is read when the gesture starts, so changing it mid-drag does nothing (MDN). And the viewport meta tag's user-scalable=no and maximum-scale are ignored by iOS Safari since iOS 10 by default; MDN also warns that turning off zoom hurts players with low vision. Scope touch-action: none to the game surface instead of locking zoom for the whole page.

A mobile-ready HTML shell

The CSS the rest of this guide assumes. Put your canvas inside #game; #ui is for any HTML menus.

<!-- in <head> -->
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; overscroll-behavior: none; }
  #game {                        /* wraps the canvas; pass it to createTouchControls() */
    position: fixed; left: 0; top: 0; width: 100%;
    height: 100vh;               /* older browsers */
    height: 100dvh;              /* tracks the visible area as browser bars move */
    touch-action: none;          /* no panning, pinch or double-tap zoom on the game */
    user-select: none; -webkit-user-select: none;  /* Safari still needs the prefix */
    -webkit-touch-callout: none; /* iOS long-press callout */
  }
  #game canvas { width: 100%; height: 100%; display: block; }
  #ui {                          /* HTML menus and buttons: keep clear of notches */
    position: absolute; inset: 0; pointer-events: none;
    padding: env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px)
             env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px);
  }
  #ui button { pointer-events: auto; }
</style>

Virtual joystick and buttons you can paste

Plain JavaScript, no dependencies. A floating stick appears where the left thumb lands, buttons on the right respond while the stick is held, each finger is tracked by pointerId, and there's a radial deadzone like the one in our Gamepad API code, so read() returns the same −1 to 1 range and both can feed one movement function. Taps that happen between two frames still show up in pressed.

// Virtual joystick + buttons for a canvas game, using Pointer Events (plain JS).
// Give `el` (your canvas or a full-size overlay) this CSS:
//   touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
const STICK_RADIUS = 60;       // CSS px from the stick's center to full deflection
const STICK_DEADZONE = 0.15;   // fraction of STICK_RADIUS; starting value, make it a setting

function createTouchControls(el, buttons) {
  // buttons: [{ name: 'jump', fx: 0.85, fy: 0.75, r: 44 }]  fx/fy = center as a fraction
  // of the element's width/height, r = hit radius in CSS px
  const stick = { id: null, ox: 0, oy: 0, x: 0, y: 0 };  // ox/oy: where the thumb landed
  const held = new Map();      // pointerId -> button name
  const down = new Set();      // button names held right now
  const pressed = new Set();   // button names pressed since the last read()

  function local(e) {          // CSS px relative to el; works at any devicePixelRatio
    const r = el.getBoundingClientRect();
    return { x: e.clientX - r.left, y: e.clientY - r.top, w: r.width, h: r.height };
  }
  function hit(p) {
    return buttons.find((b) => Math.hypot(p.x - b.fx * p.w, p.y - b.fy * p.h) <= b.r);
  }
  function syncDown() {
    down.clear();
    for (const name of held.values()) down.add(name);
  }

  el.addEventListener('pointerdown', (e) => {
    const p = local(e);
    const b = hit(p);
    if (b) {
      if (!down.has(b.name)) pressed.add(b.name);
      held.set(e.pointerId, b.name);
      syncDown();
    } else if (stick.id === null && p.x < p.w / 2) {   // floating stick: left half
      stick.id = e.pointerId;
      stick.ox = p.x; stick.oy = p.y; stick.x = 0; stick.y = 0;
    } else {
      return;                  // not ours: no capture
    }
    el.setPointerCapture(e.pointerId);  // keep this finger's events even off the element
    e.preventDefault();
  });

  el.addEventListener('pointermove', (e) => {
    if (e.pointerId !== stick.id) return;       // other fingers don't move the stick
    const p = local(e);
    let dx = (p.x - stick.ox) / STICK_RADIUS;
    let dy = (p.y - stick.oy) / STICK_RADIUS;
    const len = Math.hypot(dx, dy);
    if (len > 1) { dx /= len; dy /= len; }      // clamp to the ring
    const m = Math.min(len, 1);
    const k = m <= STICK_DEADZONE || m === 0 ? 0 : (m - STICK_DEADZONE) / (1 - STICK_DEADZONE) / m;
    stick.x = dx * k;                           // -1 (left) .. 1 (right)
    stick.y = dy * k;                           // -1 (up) .. 1 (down), like a gamepad
  });

  function end(e) {            // safe to run twice for the same pointer
    if (e.pointerId === stick.id) { stick.id = null; stick.x = 0; stick.y = 0; }
    if (held.delete(e.pointerId)) syncDown();
  }
  el.addEventListener('pointerup', end);
  el.addEventListener('pointercancel', end);       // browser took over, app switch, rotation...
  el.addEventListener('lostpointercapture', end);
  el.addEventListener('contextmenu', (e) => e.preventDefault());  // no context menu on the game

  function reset() {
    stick.id = null; stick.x = 0; stick.y = 0;
    held.clear(); down.clear(); pressed.clear();
  }
  document.addEventListener('visibilitychange', () => { if (document.hidden) reset(); });

  return {
    read() {                   // call once per frame in your game loop
      const out = {
        x: stick.x, y: stick.y,
        stickActive: stick.id !== null, stickX: stick.ox, stickY: stick.oy,  // for drawing
        held: new Set(down),
        pressed: new Set(pressed),   // taps between frames aren't lost
      };
      pressed.clear();
      return out;
    },
    reset,
  };
}

// Usage:
// const touch = createTouchControls(canvas, [{ name: 'jump', fx: 0.85, fy: 0.75, r: 44 }]);
// function frame() {
//   const t = touch.read();
//   player.vx = t.x * SPEED;
//   if (t.pressed.has('jump')) player.jump();
//   requestAnimationFrame(frame);
// }

Download touch-controls.js (the same code as a file, MIT license). For controllers, add gamepad.js from our Gamepad API guide; this file's settings are named STICK_RADIUS and STICK_DEADZONE, so the two load side by side on one page. All files: free downloads.

Prompt for your agent (Claude Code, Cursor or OpenAI Codex): “Add touch controls to this game with Pointer Events: a floating virtual joystick on the left half and action buttons on the right, tracked per pointerId with setPointerCapture, a radial deadzone, and pointercancel and lostpointercapture treated as release. Set touch-action: none and user-select: none on the game element, cancel contextmenu, pad HTML UI with env(safe-area-inset-*), and show the touch controls only after the first touch input. Don't add a fullscreen button. Add a debug overlay that shows each active pointer.”

When to show touch controls

Poki's requirements: mobile control schemes on phones and tablets (forced on tablets), keyboard instructions on desktop. Ways to decide:

Button size, devicePixelRatio and feel

Fullscreen and orientation lock

FeatureSupport (MDN compat data)What to do
element.requestFullscreen()Chrome 71, Firefox 64, Safari 16.4 on Mac. Safari on iOS: iPad only, with an overlay button you can't hide, and swiping down exits; MDN's data calls that unsuitable for some uses like games. Not on iPhoneOptional button on Android and desktop only; design for the iPhone browser bars
When it's allowedNeeds transient user activation (MDN); inside an iframe the fullscreen permission policy defaults to 'self' and the iframe needs allowfullscreenRequest it in pointerup, not pointerdown (next row)
Touch and user activationMDN's list of activation-triggering events counts pointerdown only for mouse, and pointerup and touchend for touch. Phaser's docs say the same for fullscreenStart fullscreen, audio and vibration from pointerup or touchend on mobile
screen.orientation.lock()Chrome on Android 38+, Firefox 144+; desktop Chrome always throws NotSupportedError; not in Safari or Android WebView. MDN: typically only on mobile and in fullscreen; rejects with SecurityError if the page is hidden or a sandboxed iframe lacks allow-orientation-lockDon't depend on it. Support both orientations or show a rotate overlay
Leaving fullscreenEsc, navigating away or switching tabs exits; listen for fullscreenchange (MDN)Pause and re-layout when it fires

For the rotate overlay, use @media (orientation: portrait) or (orientation: landscape). MDN notes it tests the viewport, not the device, so opening the on-screen keyboard in portrait can flip it to landscape; don't show the overlay while a text field has focus. MDN's fullscreen guide also notes that some mobile browsers ignore the viewport meta tag and block pinch zoom while in fullscreen.

On the portals: CrazyGames provides fullscreen itself and prohibits custom in-game fullscreen buttons. You set supported orientations when you submit, and the site asks players to rotate, so its docs say you don't need any orientation-lock logic. Poki asks for the full screen in portrait, landscape or both on mobile, and strongly advises portrait: portrait-playable games get more players into gameplay on average and become eligible for its Gamebar Display ads.

Poki and CrazyGames mobile rules

RulePokiCrazyGames
DevicesDesktop, mobile and tablet requiredMouse, keyboard and touch if you support mobile; must be playable in landscape on desktop (portrait games get bars)
ControlsAdaptive: mobile controls on phones and tablets (forced on tablets), keyboard instructions on desktopIntuitive controls on every device type; detect devices with the SDK's system info
OrientationFull screen in portrait, landscape or both; portrait strongly advisedSet at submission; the site asks players to rotate
FullscreenCover the full screen on mobileProvided by CrazyGames; custom fullscreen buttons prohibited. Games in the CrazyGames App open fullscreen, so pad UI for safe areas
Page behaviorGame scrolling mustn't move the parent pageuser-select: none against double-tap and long-press selection
Size and resolutionSee our publishing guide for Poki's 5 MB initial download targetInitial download of 20 MB or less for the mobile homepage; text readable at devicePixelRatio 1
iOS audioNot covered on the requirements pages we checkedAfter a call or app switch, iOS interrupts the AudioContext; call resume() in a touchend or click handler, since visibilitychange alone isn't enough

Engine notes

Testing on real devices

  1. A phone and a tablet. At least one iPhone or iPad (Safari) and one Android phone (Chrome), plus a tablet, since Poki forces mobile controls there.
  2. Two thumbs. Hold the stick, then mash the button; slide the stick thumb off the screen edge and back.
  3. Interruptions. Rotate mid-drag, pull down the notification shade, switch apps and come back. Each should release the controls (MDN lists these as pointercancel triggers) and audio should resume after the next tap.
  4. Abuse. Double-tap, long-press and pinch on the game: nothing should zoom, select or pop up.
  5. Embedded. Load the game inside an iframe on a test page as well as on its own: portals show it embedded (CrazyGames' requirements list its iframe sizes), and that's where touch-action and scrolling problems show up.

Pre-ship checklist

Related: publish an HTML5 game (itch.io, Poki, CrazyGames, Playgama) · controller support (Gamepad API) · Godot web export · responsive canvas scaling · put a web game on Steam · AI tools for playtesting and QA · how to vibe code a game

Shipping a browser game to phones? Get the VibeStack Weekly digest: new AI game-dev tools and web and Steam publishing changes, every Monday.

Sources (checked October 29, 2026): MDN Web Docs (Pointer events; Using Pointer Events; Multi-touch interaction; Element.setPointerCapture(); pointercancel and lostpointercapture events; PointerEvent.pointerType and isPrimary; touch-action; Fullscreen API and Element.requestFullscreen(); ScreenOrientation.lock(); env(); CSS length units; Window.devicePixelRatio; <meta name="viewport">; user-select; -webkit-touch-callout; overscroll-behavior; Navigator.maxTouchPoints; pointer, any-pointer and orientation media features; User activation; EventTarget.addEventListener(); Navigator.vibrate()) and MDN's browser-compat-data for version numbers; the W3C Pointer Events Level 4 Working Draft (8 October 2026); W3C WCAG 2.2 Understanding Success Criteria 2.5.8 and 2.5.5; Poki developer docs (Requirements and quality, Easy access, web engines); CrazyGames developer docs (Technical requirements, Gameplay requirements, Quality guidelines, CrazyGames App, SDK user module); Phaser 4.1.0 docs (InputConfig, InputManager, InputPlugin, TouchInputConfig, ScaleManager); Godot 4.7 docs (VirtualJoystick, TouchScreenButton, InputEventScreenTouch, InputEventScreenDrag, ProjectSettings, DisplayServer, Exporting for the Web). The code, the recommendations and the checklist are ours, not the browser makers' or the portals'. We tested the joystick code's logic with simulated pointer events, not on phones, so try it on real devices before you ship.

Get the Starter Stack ($12) Get the free weekly digest

Our picks (4)

Claude Code

AI Code Editors & Agents

Anthropic's agentic coding tool for the terminal, VS Code and JetBrains. Uses a Claude Pro/Max plan or the API.

#cli#agent
freemium

Cursor

AI Code Editors & Agents

AI-first code editor with agent mode, built on VS Code.

#editor#agent
freemium

OpenAI Codex

AI Code Editors & Agents

OpenAI's coding agent: CLI, IDE extension, web and cloud tasks. Included in ChatGPT plans (Free with limits). Unity ships an official Codex skills plugin (unity@unity-agent-plugin) for Unity 6+. The ModRetro Chromatic plugin (November 2026) builds Game Boy and Game Boy Color games as GB Studio projects, playtests them in a built-in emulator and can flash them to a Chromatic handheld cartridge.

#cli#agent
freemium

GitHub Copilot

AI Code Editors & Agents

AI pair programmer and coding agent across VS Code, JetBrains and the CLI. Free plan available; Gemini 4 Argon on Pro+ and higher.

#editor#agent#github

+ Your tool here

Reach builders, vibe coders & indie game devs. Featured listings from $49/mo.

Advertise →
🧰 The Vibe Coder's Starter Stack: AI rules files, a prompt library and a ship-it checklist. $12.
Get the pack

FAQ

How do I stop the page scrolling or zooming when players touch my HTML5 game?

Put touch-action: none on the game element, inside the game's own page; the W3C spec says touch-action doesn't carry into iframes, so a portal can't set it for you. Add user-select: none (with the -webkit- prefix for Safari) and -webkit-touch-callout: none against long-press selection and callouts, and overscroll-behavior: none on html and body against pull-to-refresh.

Should I use touch events or pointer events for a web game?

Pointer Events. They cover mouse, pen and touch with one set of handlers, give each finger a pointerId, and support pointer capture. MDN's compat data lists support from Chrome 55, Firefox 59 and Safari 13 (iOS 13). If you do use touch events on window, document or body, pass { passive: false }, because those listeners are passive by default and can't cancel scrolling.

How do I make a virtual joystick in JavaScript?

On pointerdown in the left half, store the pointerId and start position and call setPointerCapture. On pointermove for that id, divide the offset by the stick radius, clamp it to length 1 and apply a radial deadzone. On pointerup, pointercancel or lostpointercapture, reset to zero. Track buttons by pointerId in a Map so they work while the stick is held. The code on this page does all of that.

Why do my touch controls get stuck or stop mid-drag?

Usually a missing pointercancel handler. MDN lists when browsers cancel a pointer: switching apps, rotating the device with a finger down, palm rejection, the browser starting a pan or zoom, or too many simultaneous touches. Treat pointercancel and lostpointercapture like pointerup, and reset all controls when the page is hidden.

Can an HTML5 game go fullscreen on iPhone?

Not with the Fullscreen API. MDN's compat data says Safari on iOS supports element fullscreen only on iPad, with an overlay button that can't be hidden and swipe-down to exit. Design for the iPhone's browser bars with dvh units and safe-area padding instead. On CrazyGames, custom fullscreen buttons are prohibited because the site provides fullscreen.

How do I lock an HTML5 game to landscape?

screen.orientation.lock('landscape') works in Chrome on Android and Firefox 144+, typically only in fullscreen, and not in Safari or Android WebView. Support both orientations, or show a rotate-your-device overlay with an orientation media query. CrazyGames handles orientation itself if you set it in your submission; Poki strongly advises supporting portrait.

How big should touch buttons be in a mobile web game?

WCAG 2.2 sets 24×24 CSS pixels as the minimum target size (Level AA) and 44×44 as the enhanced size (Level AAA). Game buttons pressed with thumbs without looking should be bigger than both; our example uses an 88 px circle. Size and hit-test in CSS pixels, not canvas pixels.

How do I get multi-touch in Phaser?

Phaser enables one touch pointer by default. Set input: { activePointers: 3 } in the game config, or call this.input.addPointer(2) at runtime, for up to 10 pointers. Call this.scale.startFullscreen() from pointerup, not pointerdown, on touch devices.

Does Godot have a virtual joystick for web and mobile?

Yes, in Godot 4.7: the class reference has a VirtualJoystick Control with fixed, dynamic and following modes that drives the ui_* input actions by default (it isn't in the 4.5 or 4.6 docs). TouchScreenButton handles multitouch buttons. On the web, screen_set_orientation() isn't implemented, so set orientation through the portal or your HTML page.

Free download · one page + PDF · updated weekly, current edition November 16, 2026

📬 Get the VibeStack Weekly + the free AI Game Dev Stack 2026

The best AI tool for each job in a solo or indie game (3D, sprites and pixel art, animation, audio, NPCs), MCP setups for Unity, Unreal, Godot and Roblox, and which free plans you can actually ship with.

Yours free when you join the VibeStack Weekly: new AI game-dev tools and releases every Monday, 5-minute read. Unsubscribe anytime.