03 Apr

JavaScript Animations and HTML5 Vibration APIs

HTML5 Logo

First checkout this demo link on your cell phone: https://sreenath.net/demos/animation.htm

On a normal desktop browser with no Vibration hardware, you will see a ball simply bouncing on a black background. On a device with Vibration hardware and a supporting browser, you will feel the ball bounce off the sides of the window with a short vibration.

That’s new in HTML5 and JavaScript. Here how its done:

It’s that simple. 100 here is the duration to vibrate. You can also pass in an array of milliseconds, duration of vibration followed by duration of silence and so on as follows:

Now about timing the vibrations with the animation:

I use a JSON object as a Singleton for storing data about the window height, width, position of the ball, direction etc.

I have the following event handlers attached to the window load event and the window resize event: (Note that this code wont gracefully degrade in IE8 and older browsers)

My startAnimation function:

It is important that the CSS for the box1 object to move is to set its position as absolute. Otherwise the best code won’t work on it. So here’s the CSS:

Finally my Animate function.

Its important to update the direction of the movement of the box once it hits the edge and to check the direction each time before moving the box to determine which way it should be headed – to decide whether to increment or decrement the left/top property.

And my setDimensions function, required for initial loading and handling browser resize events:

Known Issues with the demo:

  1. Doesn’t handle resize due to re-orientation event of your device.
  2. As of publishing time,  Safari doesn’t support the Vibration API. That leaves out all iOS devices from enjoying this demo.

Your thoughts please..