Key Takeaways
- The Gamepad API, a proposed standard of the W3C, provides a consistent API across browsers for connecting gaming input devices like an Xbox Controller to a computer for browser-based experiences.
- The Gamepad API offers flexibility and provides access to buttons and axes with normalized values, and the Gamepad object offers detailed information about the connected gamepad’s manufacturer and model.
- The PxGamepad is a helper class that provides a higher level representation of a standard gamepad like the Xbox One controller, mapping the button and axis indices to familiar names as labeled on the Xbox controller.
- While the Gamepad API is capable of supporting multiple players with their own gamepads, future improvements might allow users to remap or customize the button functions on their gamepads, and the API offers potential for non-game scenarios like manipulating and navigating 3D models.
This article is part of a web dev series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
Gaming on the Web has come a long way with HTML5 technologies like Canvas, WebGL, and WebAudio. It’s now possible to produce high-fidelity graphics and sound within the browser. However, to provide a true gaming experience, you need input devices designed for gaming. The Gamepad API is a proposed standard of the W3C, and is designed to provide a consistent API across browsers.
The Gamepad API allows users to connect devices like an Xbox Controller to a computer and use them for browser-based experiences! If you have a gamepad, try plugging it into your computer and then press a button. You’ll see the Xbox controller below light up to mirror each movement you make!

Try it out interactively here.
This tutorial is the third in a series on Flight Arcade – built to demonstrate what’s possible on the web platform and in the new Microsoft Edge browser and EdgeHTML rendering engine. You can find the first two articles on WebGL and Web API, plus interactive code and examples for this article at flightarcade.com.
[youtube xyaq9TPmXrA]Flexible API
The Gamepad API is intelligently designed with flexibility in mind. At a basic level, it provides access to buttons and axes. Button values range from [0 .. 1] while axes range from [-1 .. 1]. All values are normalized to these ranges so developers can expect consistent behavior between devices.
The Gamepad object provides detailed information about the manufacturer and model of the connected gamepad. More useful is a mapping property which describes the general type of gamepad. Currently the only supported mapping is standard which corresponds to the controller layout used by many popular game consoles like the Xbox.
The standard controller mapping has two sticks, each of which is represented by 2 axes (x and y). It also includes a D-pad, 4 game buttons, top buttons, and triggers: all represented as buttons in the Gamepad API.
Current Xbox controllers report button state as either 0 (normal state) or 1 (pressed). However, you could imagine that future controllers could report the amount of force applied to each button press.
The Xbox D-pad also reports discrete values (0 or 1), but the sticks provide continuous values across the entire axis range [-1 .. 1]. This additional precision makes it much easier to fly the airplane in our Flight Arcade missions.
PxGamepad
The array of buttons and axes provided by the Gamepad API is forward thinking and perfect as a low level API. However, when writing a game, it’s nice to have a higher level representation of a standard gamepad like the Xbox One controller. We created a helper class named PxGamepad that maps the button and axis indices to the more familiar names as labeled on the Xbox controller.
We’ll walk through a few interesting pieces of the library, but the full source code (MIT License) is available here: https://github.com/thinkpixellab/PxGamepad
The standard Gamepad API provides button state as an array of buttons. Again, this API is designed for flexibility allowing controllers with various button counts. However, when writing a game, it’s much easier to write and read code that uses the standard mapped button names.
For example, with the HTML5 gamepad api, here is the code to check whether the left trigger is currently pressed:

The PxGamepad class contains an update method that will gather the state for all the standard mapped buttons and axes. So determining whether the leftTrigger is pressed is as simple as accessing a boolean property:

Axes in the standard Gamepad API are also provided as an array of numerical values. For example, here is the code to get the normalized x and y values for the left stick:

The D-pad is a special case, because it considered a set of four buttons by the HTML5 Gamepad API (indices 12, 13, 14, and 15). However, its common for developers to allow the dpad to be used in the same way as one of the sticks. PxGamepad provides button infomation for the D-pad, but also sythesizes axis information as though the D-pad were a stick:

Another limitation of the HTML5 Gamepad API is that is doesn’t provide button level events. It’s common for a game developer to want to activate a single event for a button press. In flight arcade, the ignition and brake buttons are good examples. PxGamepad watches button state and allows callers to register for notifications on button release.

Here is the full list of named buttons supported by PxGamepad:
- a
- b
- x
- y
- leftTop
- rightTop
- leftTrigger
- rightTrigger
- select
- start
- leftStick
- rightStick
- dpadUp
- dpadDown
- dpadLeft
- dpadRight
Obtaining the Current Gamepad
There are two methods for retrieving the gamepad object. The Gamepad API adds a method to the navigator object named getGamepads() which returns an array of all connected gamepads. There are also new gamepadconnected and gamepaddisconnected events that are fired whenever a new gamepad has been connected or disconnected. For example, here is how the PxGamepad helper stores the last connected gamepad:

And here is the helper to retrieve the first standard gamepad using the navigator.getGamepads() API:

The PxGamepad helper class is designed for the simple scenario where a single user is playing a game with a standard mapped gamepad. The latest browsers, like Microsoft Edge, fully support the W3C Gampepad API. However, older versions of some other browsers only supported pieces of the emerging specification. The PxGamepad listens for the gamepadconnected events and falls back to querying for the list of all gamepads if needed.
Future of Gamepad
While PxGamepad is focused on the simple, most common scenario, the Gamepad API is fully capable of supporting multiple players, each with their own gamepad. One possible improvement for PxGamepad might be to provide a manager-style class which tracks connection of multiple gamepads and maps them to multiple players in a game. Another might be to allow users to remap or customize the button functions on their gamepads.
We’re also excited about the potential of the Gamepad for non-game scenarios. With the rise of WebGL, we’re seeing a variety of innovative uses for 3D on the web. That might mean exploring the Mt. Everest region in 3D with GlacierWorks. Or viewing the Assyrian Collection of the British Museum thanks to CyArk’s efforts to digitally preserve important world sites and artefacts.
During the development of Flight Arcade, we frequently used Blender and other 3D tools to process models for Babylon.JS. Some developers and artists use a device called a 3D mouse to help manipulate and navigate 3D models. These devices track movement of a single knob through six axes! They make it really easy and quick to manipulate models. Beyond gaming, they’re used in a variety of interesting applications from engineering to medical imaging. While adding gamepad support to Flight Arcade, we were surprised to learn that the Gamepad API detected our 3D SpaceMouse and provided movement data for all six axes!
It’s exciting to imagine all the possibilities that the new Gamepad API offers. Now is a great time to experiment with the new Gamepad API and add precision control and a lot of fun to your next game or application!
More hands-on with JavaScript
Microsoft has a bunch of free learning on many open source JavaScript topics and we’re on a mission to create a lot more with Microsoft Edge. Here are some to check-out:
- Microsoft Edge Web Summit 2015 (a complete series of what to expect with the new browser, new web platform features, and guest speakers from the community)
- Build of //BUILD/ and Windows 10 (including the new JavaScript engine for sites and apps)
- Advancing JavaScript without Breaking the Web (Christian Heilmann’s recent keynote)
- Hosted Web Apps and Web Platform Innovations (a deep-dive on topics like manifold.JS)
- Practical Performance Tips to Make your HTML/JavaScript Faster (a 7-part series from responsive design to casual games to performance optimization)
- The Modern Web Platform JumpStart (the fundamentals of HTML, CSS, and JS)
And some free tools to get started: Visual Studio Code, Azure Trial, and cross-browser testing tools – all available for Mac, Linux, or Windows.
This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ modern.IE.
Frequently Asked Questions about the Gamepad API
What is the Gamepad API?
The Gamepad API is a web-based interface that allows developers to access and respond to signals from a gamepad or controller. This API is designed to work with any type of gamepad, making it a versatile tool for game developers. It provides a way to interact with the gamepad directly, without needing to go through a third-party software or driver.
How does the Gamepad API work?
The Gamepad API works by detecting the inputs from the gamepad and translating them into actions within the game. It does this by listening for specific events, such as button presses or joystick movements, and then triggering the corresponding action in the game. This allows for a more immersive and interactive gaming experience.
How can I use the Gamepad API in my own games?
To use the Gamepad API in your own games, you will need to include it in your game’s code. This involves calling the API’s functions and listening for the events it generates. You can then use these events to control aspects of your game, such as character movement or menu navigation.
What types of gamepads are compatible with the Gamepad API?
The Gamepad API is designed to be compatible with a wide range of gamepads. This includes standard gamepads with buttons and joysticks, as well as more specialized controllers like steering wheels or flight sticks. The API can also handle multiple gamepads at once, allowing for multiplayer games.
Can I use the Gamepad API with other APIs?
Yes, the Gamepad API can be used in conjunction with other APIs to create more complex games. For example, you could use the Gamepad API to control character movement, while using another API to handle game physics or graphics.
Is the Gamepad API supported by all browsers?
While the Gamepad API is a web-based interface, not all browsers currently support it. However, most modern browsers, including Chrome, Firefox, and Edge, do support the Gamepad API. It’s always a good idea to check the current browser support for the API before starting development.
What are some common issues developers face when using the Gamepad API?
Some common issues developers face when using the Gamepad API include detecting the correct gamepad, handling multiple gamepads, and dealing with different button layouts. These issues can usually be resolved by carefully reading the API documentation and testing the game thoroughly.
Can the Gamepad API be used for mobile games?
While the Gamepad API is primarily designed for use with desktop browsers, it can also be used for mobile games. However, this requires a gamepad that is compatible with the mobile device, and the user experience may not be as smooth as with a desktop game.
How can I test the Gamepad API?
You can test the Gamepad API by connecting a gamepad to your computer and running a game that uses the API. You can then press buttons on the gamepad and see if the corresponding actions are triggered in the game.
Where can I learn more about the Gamepad API?
There are many resources available online for learning more about the Gamepad API. This includes the official API documentation, as well as tutorials and guides on various game development websites. You can also find examples of games that use the API to see it in action.
The above is the detailed content of A True Gaming Experience with the Gamepad API. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools