Phaser Game Development: 2D HTML5 Games
In This Guide
- What Is Phaser
- Why Choose Phaser for 2D Games
- Phaser 3 and Phaser 4
- Core Architecture: Scenes and the Game Loop
- Game Objects: Sprites, Text, and More
- Rendering in Phaser
- Physics Systems: Arcade and Matter.js
- Tilemaps and Level Design
- Input Handling
- Audio, Cameras, and Effects
- Building for Mobile and Progressive Web Apps
- Publishing and Monetizing Your Phaser Game
What Is Phaser
Phaser is a JavaScript game framework designed specifically for 2D browser games. It was first released in 2013 by Richard Davey under the studio name Photon Storm, and it quickly became one of the most popular HTML5 game frameworks in the world. Phaser provides a complete game development toolkit that includes a rendering engine, physics simulation, sprite management, animation system, input handling, asset loading pipeline, and audio playback.
The framework runs on both WebGL and HTML5 Canvas, automatically selecting the best renderer for the player's browser. Games built with Phaser work on desktop browsers, mobile browsers, and can be wrapped for app stores or distributed as Progressive Web Apps. The framework is written in JavaScript and supports TypeScript through official type definitions, making it accessible to web developers who already know the language.
Phaser follows a scene-based architecture where each game state, such as a menu screen, gameplay level, or game-over screen, is a separate scene with its own preload, create, and update methods. This structure keeps game code organized and makes it straightforward to manage transitions between different parts of your game. The framework handles the game loop internally, calling your update function at each frame so you can focus on game logic rather than rendering timing.
The project is hosted on GitHub under an open-source MIT license, meaning you can use it for free in personal, educational, and commercial projects. Photon Storm also offers commercial support and premium plugins for teams that need dedicated assistance. The framework has been used by studios, indie developers, educators, and hobbyists across the world, with thousands of published games demonstrating its versatility.
Why Choose Phaser for 2D Games
Phaser occupies a unique position in the game development landscape because it targets the browser as a first-class platform. Unlike Unity or Godot, which export to web as a secondary target, Phaser is built from the ground up for web delivery. This means smaller file sizes, faster load times, and no plugin requirements for players. A typical Phaser game loads in seconds and plays immediately in any modern browser without downloads or installations.
The framework has a large and active community that has produced thousands of tutorials, examples, plugins, and open-source games. The official Phaser website hosts over 1,800 code examples covering nearly every feature, and the documentation is thorough enough to serve as a learning resource on its own. Community forums, Discord servers, and GitHub discussions provide support for developers at every skill level.
For developers coming from web development backgrounds, Phaser requires no new tooling beyond what you already use. You write JavaScript or TypeScript, use npm for package management, and can integrate with any build tool you prefer, whether that is Vite, Webpack, or a simple script tag. There is no proprietary editor to learn, no binary assets to manage, and no compilation step beyond standard JavaScript bundling.
Phaser also excels at rapid prototyping. A basic game with sprites, physics, and input can be built in under 100 lines of code. The framework handles boilerplate like game loop management, asset caching, and device scaling, letting you iterate on gameplay ideas without wrestling with engine internals. Many game jams feature Phaser entries because of how quickly you can go from concept to playable prototype.
Cross-platform reach is another significant advantage. A single Phaser codebase runs on Windows, macOS, Linux, Android, and iOS through the browser. With PWA deployment or a native wrapper like Capacitor, you can reach app stores as well. This makes Phaser particularly appealing for solo developers and small teams who cannot maintain separate codebases for each platform.
Phaser 3 and Phaser 4
Phaser 3 was released in 2018 as a complete rewrite of Phaser 2. It introduced a modern scene system, a new rendering pipeline, and a vastly expanded API. Phaser 3 matured through dozens of releases, with version 3.90 being the final major Phaser 3 release. The Phaser 3 ecosystem includes extensive documentation, thousands of examples, and a large library of community plugins and tutorials.
Phaser 4, released in early 2026, builds on everything learned from Phaser 3 while replacing the entire rendering pipeline. The new version uses a node-based renderer architecture where each render node handles a single task, WebGL state is fully managed, and context restoration is handled automatically. This makes Phaser 4 significantly faster than its predecessor, particularly on mobile devices where GPU resources are limited.
Key improvements in Phaser 4 include a unified filter system that replaces the separate FX and Mask systems from Phaser 3. Filters like blur, glow, shadow, pixelate, bloom, and color matrix are all part of a single, consistent API. The renderer uses index buffers for quads, reducing vertex upload costs by roughly a third, and multi-texture batching has been optimized to avoid unnecessary batch breaks on mobile hardware.
One of the most notable additions in Phaser 4 is SpriteGPULayer, which can render up to one million sprites in a single draw call. This feature achieves performance up to 100 times faster than traditional sprite rendering, opening up possibilities for particle-heavy effects, bullet-hell games, and large-scale simulations that were impractical in Phaser 3.
If you are starting a new project, Phaser 4 is the recommended choice. If you are maintaining an existing Phaser 3 game, the migration path is well documented and most game logic transfers directly, with changes primarily in rendering and effects code. The Phaser team provides migration guides and the community has published comparison articles to help developers transition.
Core Architecture: Scenes and the Game Loop
Every Phaser game starts with a configuration object that defines the game dimensions, renderer type, physics settings, and the list of scenes. The Phaser.Game constructor takes this configuration and initializes the rendering context, input manager, sound manager, and all other subsystems. Once created, the game object manages the main loop and coordinates all active scenes.
Scenes are the fundamental organizational unit in Phaser. Each scene is a class with three core methods: preload, create, and update. The preload method loads assets like images, spritesheets, audio files, and tilemaps. The create method runs once after all assets are loaded and is where you set up game objects, physics bodies, input listeners, and initial game state. The update method runs every frame and contains your game logic, such as moving characters, checking collisions, and updating scores.
A typical game might have a BootScene that loads the minimum assets needed for a loading screen, a PreloadScene that loads all game assets while showing a progress bar, a MenuScene for the title screen, a GameScene for the actual gameplay, and a GameOverScene for results. Each scene can be started, stopped, paused, resumed, or restarted independently, and multiple scenes can run simultaneously.
Running multiple scenes at once is particularly useful for layered interfaces. You might have a GameScene running the gameplay while a HUDScene draws the score, health bar, and minimap on top. The HUD scene receives its own update calls and can respond to events from the game scene without the two being tightly coupled. A PauseScene can overlay both, dimming the background while showing pause menu options.
The game loop in Phaser uses requestAnimationFrame to sync with the browser's refresh rate, typically 60 frames per second. The framework provides both a fixed time step for physics calculations and a variable delta time for smooth visual updates. This ensures that game logic remains consistent regardless of the actual frame rate, which is particularly important for physics-based games where timing directly affects gameplay outcomes.
Game Objects: Sprites, Text, and More
Game objects are the visual and interactive elements that make up your game world. The most common game object is the Sprite, which displays an image or animation frame at a specific position in the scene. Sprites can be scaled, rotated, tinted, and made interactive. They support origin points for precise positioning, blend modes for visual effects, and masks for clipping regions.
Beyond sprites, Phaser provides a rich set of game objects for different purposes. Text objects render strings using web fonts or bitmap fonts with full control over alignment, word wrapping, color, and styling. Graphics objects let you draw shapes, lines, curves, and filled polygons programmatically, which is useful for debug visualization, procedural art, or UI elements. Containers group multiple game objects together so they can be moved, scaled, and rotated as a single unit while maintaining their relative positions.
TileSprites repeat a texture across an area and support scrolling, making them ideal for parallax backgrounds that move at different speeds to create a sense of depth. Particles create dynamic visual effects like explosions, fire, rain, smoke, sparks, and magic spells using configurable emitters that control lifetime, speed, gravity, scale, rotation, color, and transparency over time.
Animation in Phaser is handled through the Animation Manager. You define named animations from sequences of frames in a spritesheet, specifying the frame rate, loop behavior, and whether the animation should yoyo (play forward then backward). Once defined, any sprite can play the animation by name. The system supports callbacks for specific frames, completion events, and chaining animations together. Integration with physics means you can switch animations based on a character's velocity or collision state, such as playing a jump animation when the character leaves the ground.
Game objects are managed through the scene's display list, which determines rendering order. Objects added later appear on top of earlier objects, and you can change depth values to control layering explicitly. The display list is optimized for efficient rendering, batching similar objects together to minimize draw calls and maximize GPU throughput.
Rendering in Phaser
Phaser supports two rendering backends: WebGL and Canvas. WebGL is the default and preferred renderer because it offloads rendering to the GPU, enabling hardware-accelerated graphics with support for shaders, blend modes, and post-processing effects. Canvas rendering is available as a fallback for environments that do not support WebGL, though this situation is increasingly rare in modern browsers.
The WebGL renderer in Phaser 4 uses a node-based architecture that manages rendering state carefully. Each render node is responsible for a single task, such as drawing a batch of sprites, rendering text into a texture, or applying a visual filter. This design prevents the state management issues that could cause visual glitches in earlier versions and makes it straightforward to extend the renderer with custom rendering logic for specialized visual effects.
Multi-texture batching is a key performance feature that reduces the number of draw calls needed to render a scene. Instead of switching textures for each sprite, the renderer can bind multiple textures simultaneously and batch sprites that use different textures into a single draw call. The number of texture units available depends on the GPU, but most modern devices support at least 8 simultaneous textures, and desktop GPUs often support 16 or more.
The filter system provides post-processing effects that can be applied to individual game objects, cameras, or the entire game output. Available filters include blur, glow, drop shadow, pixelate, bloom, vignette, color matrix transformations, gradient mapping, and custom blend modes. Filters can be combined and animated over time for dynamic visual effects like screen shake with blur, damage vignette pulses, or transition wipes between scenes.
Render textures let you draw game objects to an off-screen buffer that can then be used as a texture for other objects. This enables dynamic reflections, fog of war effects, minimap displays, and pre-rendering of complex composite sprites. Phaser also supports custom shaders for developers who need full control over the rendering pipeline for unique visual styles.
Physics Systems: Arcade and Matter.js
Phaser includes two built-in physics engines: Arcade Physics and Matter.js. Arcade Physics is a lightweight, axis-aligned bounding box (AABB) system designed for performance and simplicity. It handles rectangular and circular collision bodies, gravity, velocity, acceleration, drag, and bounce. Arcade Physics is the right choice for platformers, top-down shooters, endless runners, and most 2D games where precise polygon collision is not required.
With Arcade Physics, you enable physics on a sprite by adding it to a physics group, and the sprite immediately gains access to velocity, acceleration, gravity, and collision detection properties. The system supports static bodies that do not move, such as platforms, walls, and ground tiles, and dynamic bodies that respond to forces and collisions. You can set collision callbacks that fire when two objects overlap or collide, giving you a place to handle damage, score changes, sound effects, or game state transitions.
Matter.js is a full-featured rigid body physics engine that supports convex polygon collision shapes, compound bodies made from multiple shapes, constraints and joints that connect bodies, and realistic physical properties like friction, restitution, density, and air resistance. Matter.js is more computationally expensive than Arcade Physics but enables games that require accurate physical simulation, such as physics puzzles, construction games, ragdoll characters, or games with complex mechanical interactions like gears and levers.
Both physics systems integrate with Phaser's game objects and scene system. You can mix physics-enabled and non-physics objects in the same scene, and switching between Arcade and Matter.js is a configuration change rather than a major code rewrite. Collision groups and categories let you control which objects interact with each other, so projectiles can pass through friendly characters while hitting enemies, or certain platforms can be walked through from below but landed on from above.
For most 2D games, Arcade Physics provides the best balance of features and performance. Its simplicity means fewer bugs related to physics edge cases, and its performance means you can have hundreds of physics bodies active simultaneously without frame drops. Reserve Matter.js for games where the physics simulation itself is a core gameplay mechanic.
Tilemaps and Level Design
Tilemaps are the standard approach for building game levels in 2D games, and Phaser has thorough tilemap support. The framework can load maps created in Tiled, the popular open-source map editor, importing layers, object groups, tile properties, and collision data directly from exported JSON files. This workflow lets level designers work in a dedicated visual editor while programmers handle game logic in code.
A tilemap consists of one or more layers, each composed of tiles from a tileset image. Layers can represent different visual depths, such as a ground layer painted with grass and dirt, a decoration layer with trees and rocks, and a foreground layer with leaves and branches that appear in front of the player. Each tile can have custom properties defined in Tiled, such as collision flags, damage values, surface type identifiers, or animation triggers, which Phaser makes available through its tilemap API.
Collision with tilemaps is handled efficiently through the physics system. You can mark specific tiles or tile indices as collidable, and Phaser automatically generates collision bodies for those tiles. The collision system merges neighboring collidable tiles into larger rectangular bodies to reduce the physics workload, which is important for large maps with thousands of tiles. Object layers in Tiled can place spawn points, trigger zones, item pickups, enemy positions, and other game elements that Phaser reads as positioned objects with custom properties.
Phaser supports both orthogonal (standard grid) and isometric tilemap rendering, covering the two most common perspectives in 2D games. Dynamic tilemaps allow you to modify tiles at runtime, enabling destructible terrain, procedural level generation, player-built structures, or environmental changes triggered by game events. The tilemap camera system handles scrolling and culling automatically, rendering only the tiles that are visible on screen for optimal performance even on maps that are thousands of tiles wide.
Input Handling
Phaser provides a unified input system that handles keyboard, mouse, touch, and gamepad input through a consistent API. The keyboard manager tracks the state of every key, letting you check whether a key is currently held down, was just pressed this frame, or was just released this frame. You can create cursor key objects for common WASD or arrow key movement patterns, or listen for specific key combination events for abilities and shortcuts.
Mouse and touch input is handled through the pointer system. Phaser abstracts mouse clicks and touch taps into a single pointer interface, so the same code works on both desktop and mobile without branching. The framework supports multi-touch through multiple pointer objects, enabling pinch-to-zoom, two-finger rotation, and other multi-touch gestures. You can make any game object interactive by enabling input on it, which adds click, hover, drag, and drop functionality with customizable hit areas.
Gamepad support is built into Phaser through the browser's Gamepad API. The framework detects connected controllers, maps their buttons and analog sticks to a standard layout, and provides the same press, release, and held state tracking as the keyboard system. This makes it straightforward to add controller support alongside keyboard and touch controls, which is increasingly expected by players on both desktop and mobile platforms.
For games that need complex input schemes, you can build input profiles that map abstract game actions like "jump," "attack," or "interact" to specific keys, buttons, or touch gestures. This abstraction layer makes it easy to offer remappable controls, support multiple input devices simultaneously, and adapt the control scheme based on the active input device. Several community plugins extend the input system with virtual joysticks, on-screen buttons, and gesture recognizers for mobile-first game designs.
Audio, Cameras, and Effects
Phaser's sound system supports both Web Audio API and HTML5 Audio, automatically selecting the best option for the player's browser. The Web Audio backend provides low-latency playback, precise volume control, stereo panning, and the ability to play dozens of sounds simultaneously without performance issues. You can load audio as individual files or as audio sprites, where multiple short sounds are packed into a single file with timing markers, reducing HTTP requests and improving load times.
Sound objects support looping, seeking, rate adjustment for pitch effects, and spatial audio positioning relative to the camera. You can create sound groups for managing background music separately from sound effects, with independent volume controls for each group. The audio system also handles the browser's autoplay restrictions gracefully, requiring user interaction before playing audio and resuming playback after the restriction is cleared.
The camera system controls what portion of the game world is visible on screen. Each scene has at least one camera, and you can create additional cameras for split-screen multiplayer, minimap displays, or picture-in-picture effects. Cameras support smooth following of game objects with configurable deadzone and lerp values, shake effects for impact feedback, fade transitions for scene changes, zoom for dramatic moments, rotation for disorientation effects, and scroll bounds that prevent the camera from showing areas outside the game world.
Tweens provide smooth interpolation of any game object property over time, making them essential for animations, UI transitions, and game feel. You can tween position, scale, rotation, alpha, tint, or any numeric property with easing functions that control the acceleration curve. The timeline system lets you sequence multiple tweens and callbacks into choreographed sequences for cutscenes, tutorials, or complex UI animations. Combined with the particle system and camera effects, these tools let you add the visual polish that separates good games from great ones.
Building for Mobile and Progressive Web Apps
Phaser games run natively in mobile browsers, but optimizing for mobile requires attention to input, performance, and screen scaling. The Scale Manager handles responsive design, offering multiple scaling modes that adapt your game to different screen sizes and orientations. You can choose to scale the game to fit the screen while maintaining aspect ratio, stretch to fill the entire viewport, or use a fixed size with letterboxing. Full-screen support is built in, and you can lock the orientation to landscape or portrait depending on your game's design.
Touch input works through the same pointer system as mouse input, but mobile games often benefit from virtual joysticks, on-screen buttons, or swipe-based controls. The Phaser community has developed several plugins for these UI elements, and you can build custom touch controls using interactive game objects positioned relative to the camera rather than the game world. Good mobile controls respond immediately, provide visual feedback, and have generous hit areas to account for imprecise finger taps.
Performance on mobile requires careful management of draw calls, texture memory, and JavaScript execution time. Use texture atlases to pack sprites into fewer images, minimize the number of active physics bodies, and avoid complex calculations in the update loop. Phaser's multi-texture batching and sprite culling help automatically, but the biggest performance gains come from thoughtful game design that keeps the number of simultaneous active objects within the device's capabilities.
Progressive Web App deployment allows your Phaser game to be installed on a player's home screen and played offline. A PWA requires a service worker for caching game assets and a web manifest file that defines the app name, icon, theme color, and display mode. Once installed, a PWA game launches in full screen without browser chrome, loads instantly from the local cache, and feels like a native app. This approach provides a native-like experience without the overhead of app store submission, review processes, or platform fees.
For app store distribution, tools like Capacitor or Cordova wrap your Phaser game in a native container that can be submitted to the Apple App Store and Google Play Store. These wrappers provide access to native device features like push notifications, in-app purchases, haptic feedback, and device sensors while keeping your game code unchanged. The trade-off is the additional work of maintaining native build configurations and complying with app store guidelines.
Publishing and Monetizing Your Phaser Game
Web games have multiple distribution channels, each with its own audience and revenue model. You can host your game on your own website and generate revenue through display advertising with Google AdSense or similar ad networks. Self-hosting gives you complete control over the player experience and keeps all revenue, but requires you to drive your own traffic through SEO, social media, or content marketing.
Game portals like itch.io, Newgrounds, CrazyGames, and Poki accept HTML5 games and provide built-in audiences of players actively looking for browser games. Some portals offer revenue sharing based on ad impressions, while others allow you to set your own price for premium games. Itch.io is particularly popular for indie developers because it supports name-your-price downloads, community features, and game jam hosting.
Licensing is a monetization path where game publishers pay a flat fee or ongoing revenue share for the rights to host your game on their platform or white-label it for their clients. The HTML5 game licensing market is active globally, with publishers in Europe, Southeast Asia, South America, and the Middle East regularly acquiring games. Publishers typically look for polished games with broad appeal, fast loading times, and clean, well-structured code that can be easily localized or reskinned.
Ad-based monetization works well for web games because players expect free-to-play browser games. Common ad formats include pre-roll video ads that play before the game starts, interstitial ads shown between levels or after game over, and rewarded video ads that give players an in-game benefit like an extra life or power-up in exchange for watching an ad. Rewarded ads tend to have the highest engagement and player acceptance because the player chooses to watch them for a tangible benefit.
If you choose app store distribution through a native wrapper, you gain access to in-app purchases, subscription models, and premium pricing. The trade-off is the 15-30% revenue share that Apple and Google take from each transaction, plus the work of app store submission, compliance with platform guidelines, age ratings, and ongoing updates to maintain compatibility with new OS versions. Many developers use a hybrid approach, offering a free web version supported by ads and a premium app store version with no ads and additional content.