Haptics
The haptics capability lets a Web Lens give physical feedback by vibrating the phone. Play a single impact, or build a pattern of taps and buzzes. It works on iOS and Android, and any Web Lens can use it.
Check snapchat.isSupported('haptics') after init() resolves, and keep your Lens working without haptics. isSupported() returns false until then, so a check at page load always reads as unsupported. It also returns false on a device that can't play haptics.
await snapchat.init();
if (snapchat.isSupported('haptics')) {
await snapchat.haptics.impact('heavy');
}
Play an impact
impact() plays one short impact. Pass a style of 'light', 'medium', 'heavy', or 'soft'. The default is 'medium':
button.addEventListener('click', () => snapchat.haptics.impact('light'));
Play a pattern
pattern() plays a timeline of taps and buzzes. Pass an array of events in time order. Events can't overlap, and the whole pattern lasts up to 1000 ms.
await snapchat.haptics.pattern([
{ t: 0, type: 'tap', intensity: 0.5 },
{ t: 80, type: 'tap' },
]);
Each event has these fields:
| Field | Type | Description |
|---|---|---|
t | Integer | When the event starts, in milliseconds from the pattern's start. |
type | 'tap', 'buzz' | A short tick, or a sustained vibration. |
duration | Integer | Required for a buzz, from 1 to 500 milliseconds. |
intensity | Number | Optional, from 0 to 1. The default is 1. |
A pattern takes 1 to 16 events.
Recipes
These patterns approximate the success, warning, and error feels on iOS:
const SUCCESS = [
{ t: 0, type: 'tap', intensity: 0.5 },
{ t: 80, type: 'tap' },
];
const WARNING = [
{ t: 0, type: 'tap' },
{ t: 150, type: 'tap', intensity: 0.5 },
];
const ERROR = [
{ t: 0, type: 'tap' },
{ t: 60, type: 'tap' },
{ t: 120, type: 'tap' },
];
snapchat.haptics.pattern(SUCCESS);
When nothing plays
impact() and pattern() both resolve with nothing, and a call that plays nothing doesn't reject. Nothing plays when:
- The Snapchatter turned haptics off in the device settings: System Haptics on iOS, or Vibration & haptics on Android.
- The call comes within 50 ms of the last haptic, or while a pattern is still playing.
A call with invalid arguments rejects with ERR_INVALID_PARAMS.
Two limits to plan for:
- Android 7 and lower doesn't support haptics, so
isSupported('haptics')isfalsethere. - The feel of a style varies between devices, so don't depend on an exact sensation.
Test on the desktop
The desktop stub checks the arguments of haptics calls the same way a device does, so invalid events reject while you build. Nothing vibrates, so test the feel on a phone.
HapticsAPI in the API reference lists every method and type.