Getting a car to spin in a browser without jerkiness is no mean feat. In the second instalment of our Things That Spin series, Nicole Schloeter, Senior Developer at Tribal Worldwide London, explains how she managed to achieved it.

(This is only an animated GIF to illustrate the article. To see the proper implementation visit vw.co.uk/new/troc/360)

When we initially approched this challenge, we considered using a video format to playback the 360° rotation of a car. However, as we started working, we found the best approach was to create a sequence made up of 360° angles of the car and then draw those sequences into the HTML Canvas object instead, 1 frame (angle) at a time. We then refreshed the canvas with a new image from the sequence as soon as the browser’s was able to do so, via the window.requestAnimationFrame();

We chose canvas because we wanted the spinning animation and direction to be altered by the user, with added velocity and intensity to give a realistic feel — and scrubbing the video backwards, doesn’t really work. It turned out that canvas was pretty good at displaying new bitmap images drawn at a very fast rate, consistently throughout various devices.

By taking a similar approach to Adobe Flash, we achieved the physics aspect of the animation by adding Flash’s equivalent of an EnterFrame by setting an interval, which added the correct velocity and took user interaction into consideration by listening to mouse/touch events.

JavaScript logic then translated these physics into which angle of the 360° image sequence needed to be drawn next. We had to add in a speed cap, to avoid being able to touch/push the virtual car into a vigorous spin, which would have contradicted the characteristics of the real solid, heavy car.

Our next challenge was the file size of having to load in 360° images and, consequently, the waiting time while all separate server requests are made and loaded in by the browser.

The obvious choice to reduce this, is by only loading in the images at the size needed for the current screen — which is a larger and more complex task than it initially sounds, as users can change orientations and thus increasing widths or resize their browser windows.

Additionally, we found that we could save on loading times for smaller width devices — like mobile phones — as we didn’t need to show every single 360° angle to create a smooth full turn rotation.

That meant we could skip a few frames and only draw every 8th angle! On tablet sized devices we programmatically started to decrease the frames being skipped until we end up showing every 2nd — 4th frame on desktop screens.

Even on a very slow spin, the human eye doesn’t really mind not being served all 360 degrees of the car — it still feels very smooth. If I say so myself.

See it here: vw.co.uk/new/troc/360