The Future of Javascript Animation with Famo.us

A guide to making your web apps feel native

After much anticipation, hype and controversy, Famo.us is finally being released today for limited public consumption. When I first saw the Famo.us webpage in late 2012, I was intrigued by what I thought was impossible to do on the web. Suspending disbelief for a moment, I began to wonder what code would look like if the animation magic I was seeing were suddenly possible to write in JavaScript.

Ultimately, developing in Famo.us is straightforward; however the concepts do differ from standard web development. In this primer I’m going to go over why Famo.us is different, the basics of writing Famo.us apps, and a list of resources to help you become a guru.

These days, web browsers apply hardware acceleration to certain CSS properties. When rendering a typical webpage, you can gain the benefits of this acceleration if you trigger CSS based animations. The browser still has to work hard to recompute the layout of your page from a change to the DOM. In practice this means that if your app is making changes to the DOM that require the browser to re-layout your page, you’ll lose hardware acceleration and generally see inconsistent and slow performance.

Famo.us is built around a neat idea: by directly using the CSS matrix3d transform in combination with the window.requestAnimationFrame function, you can describe the complete layout and animation of your app in a way that’s hardware accelerated with consistent performance.

It’s a stroke of genius, but in order to implement that simple idea you need a sophisticated math library to help translate your app’s UI into the series of matrix transformations that get pushed to the GPU. This library is Famo.us.

Surfaces

The basic building blocks of a Famo.us application are Surfaces. Surfaces are simply divs that contain HTML. They make up your app at the most granular level and often do not contain sophisticated layout or content that you want to animate within the surface. A typical app is built out of many surfaces containing mostly text or images and targeted with basic visual CSS.

The Scene Graph contains your app’s surfaces along with Transforms. Transforms are used to position surfaces and thereby layout the UI of your app. They are also used to describe animation.

DemoSource

var mainCtx = Engine.createContext();

// Create a surface, content is html
var surface = new Surface({
    size:    [100, 100],
    content: "<span>Click To<br/>Move<br/>Surface</span>",
    classes: ["test-surface"]
});

// Define Matrix transforms for start/end positions
// and an easing curve to transition between them
var startPos = Transform.translate(20, 20, 0);
var endPos = Transform.translate(150, 200, 0);
var transform = new Modifier({ transform: startPos });
var easeTransition = { duration: 500, curve: Easing.inOutCubic };

// Apply the transition on click and switch start/end
surface.on("click", function (e) {
  transform.setTransform(endPos, easeTransition);
  startPos = [endPos, endPos = startPos][0];
});

mainCtx.add(transform).add(surface);
A basic Scene composed of a Surface with an Easing Curve based Transition.

The Render Loop ties all of this together. That is, the web browser calls Famo.us’ requestAnimationFrame callback function at up to 60 frames per second (FPS) forever. Each time it’s called, Famo.us evaluates it’s scene graph, does a bunch of complicated math and updates the matrix3d transform of all of the surfaces. If there is any change to this property between iterations of the loop, the browser will move/rotate/scale the surfaces via the GPU and this will be perceived by the user as a smoothly animating surface.

As an added bonus, Famo.us also includes a physics engine. This allows you to define animations that follow the laws of physics (such as springs) as well as collision detection.

DemoSource

var mainCtx = Engine.createContext();
var PE = new PhysicsEngine();

// Create a surface, content is html
var surface = new Surface({
  size: [100, 100],
  content: "<span>Click To<br/>Spring<br/>Surface</span>",
  classes: ["test-surface"]
});

// Create a physical particle with position (p), velocity (v), mass(m)
var particle = new Particle({
  mass: 1,
  position: [0, 0, 0],
  velocity: [0, 0, 0]
});

// Create a spring that will act on the particle
var spring = new Spring({
  anchor: [0, 0, 0],
  period: 400,  // <= Play with these values :-)
  dampingRatio: 0.07, // <=
  length: 0
});

// Apply a force on the surface when its clicked
surface.on("click", function (e) {
  particle.applyForce(new Vector(0, 0, -0.005 * 100));
});

// Link the spring, particle and surface together
PE.attach(spring, particle);
PE.addBody(particle);

// Create the scene, applying a top level modifier to center
// the scene vertically in the viewport
mainCtx.add(new Modifier({ origin: [.5, .5] })).add(particle).add(surface);
mainCtx.setPerspective(1000);
Physics like this are impossible to animate with css.

Components

Famo.us ships with a number of high-level Views that combine these low level techniques into components that are quick and easy to compose in sophisticated applications. One such component that’s worth examining is the ScrollView, because it illustrates how a developer might use the fundamentals of Famo.us to build something reusable – that is Edit: impossible (I’m not trying to make a contentious statement with this post) to do without Famo.us.

A ScrollView implements a scrollable list of items with a tactile ‘bounce’ at the edges of the list. This interaction is often seen on smartphones and modern browsers. Counter to intuition, the ScrollView uses none of the browser’s built in scrolling functionality. Instead, it’s a list of surfaces that are animated in response to touch/drag events generated by the user. The list clips at the edge of the window, and when the last item is reached, a physics spring animation is actuated. Apart from generating the events and drawing the surfaces to the screen, the browser does no other work for us. The benefits of this approach are twofold:

DemoSource

var mainCtx = Engine.createContext();

// Create a scrollview and array to hold surfaces
var scrollView = new Scrollview();
var surfaces = [];

// Create a numbered surface
function createSurface(number) {
  return new Surface({
    size: [undefined, 100],
    content: "Surface " + number,
    classes: ["test-surface", (i % 2 ? "odd" : "even")]
  });
}

// Add many surfaces to the scrollView
for (var i = 0; i < 20; i++) {
  surfaces.push(createSurface(i));
}

// Include the surfaces in the scrollview and pipe
// events to it from the engine
scrollView.sequenceFrom(surfaces);
scrollView.subscribe(Engine);

mainCtx.add(scrollView);
A ScrollView is an example of Famo.us’ UI composition.

You have complete control over the behaviour of the bouncy list. For example you could alter how the list accelerates or the amount and duration of springy-ness in the list. You could even invent your own unique type of a tactile-feedback-powered-list that uses a completely different effect.
The performance of your app remains consistent and is under your control.

Our studio is extremely excited about the new doors that will open for web developers thanks to Famo.us –especially in the area of mobile. Whilst we’ve been shipping ‘native’ mobile web apps using technologies like PhoneGap for quite some time, we would like to compete with the speed and sophistication of true native UIs.

That’s why Famo.us is a game changer.

Edit: I’ve published the code for the examples in the repository below, up to date with the recently open sourced famo.us library.

References

Code for the examples above: https://github.com/percolatestudio/famous-blog-examples
Famo.us: http://famo.us
Demos: http://codepen.io/befamous
Repository: https://github.com/Famous/famous
Guides: https://github.com/Famous/guides/tree/master/dev
Image: Maciej Lulko

27 Comments

  1. mh

    Have the people complaining about the terms & conditions actually read them? What point concerns you exactly? I just read their branding / privacy as well as Famo.us’ terms and conditions, and I see nothing here that is different to any other company looking to structure a commercial offering on-top of their open-source one.

    Also, the open-source offering is under the Mozilla public license. That is all that should concern you unless you are a contributing developer to Famo.us, or, you have signed an additional contract for paid services directly with them.

    I hope developers aren’t dissuaded from Famo.us based on trollish comments — I can see no other way to make sense of them.

    Aug 25, 2014 Reply
  2. Bakyt

    Thank you so much! What a great article.

    Jul 12, 2014 Reply
  3. Andrew Cooney

    Partly to answer my own question, I’ve just had a tweet from the team saying the appstore publishing wrapper is currently in Beta. It will be released ‘when it’s ready’

    May 20, 2014 Reply
  4. Andrew Cooney

    I like the look of the demos and I’ve decided to invest some time trying famo.us out.

    I use Phonegap at the moment which is horrible in several ways, performance being a major one, but it does allow access to the phone’s resources and I’m not clear to what extent I can do that with famo.us – contacts I guess probably not, GPS via HTML5?

    The other aspect I’m unclear on is how you publish a Famo.us app to the app store.. I get that this is being worked on by the team but does that mean you can’t in the meantime or is there another way? It’s a pig to publish via xcode or eclipse with Phonegap but it does work.

    May 20, 2014 Reply
  5. Michael Kuczera

    Great article. I´m testing it right now and it´s incredible. For the meteor Users: There is a famo.us tutorial in development http://famous-tutorial.meteor.com/

    May 8, 2014 Reply
  6. Dominic Claxton

    An interesting framework but I don’t know what the fuss is all about regarding the terms and conditions. This is standard practise amongst license distributers and as far as I can see refers to the services on their website rather than use of the codebase.

    Apr 27, 2014 Reply
  7. zaw win aung

    Very nice tutorial / article, I’ve just been messing with Famo.us this week.
    Nice so far, just waiting to enter their training area (“University”), just been learning from their examples and the github source.

    Done some demos, have a look: –

    https://c9.io/flyingmachete_1/famous_stress_test_1/workspace/index.html

    https://c9.io/flyingmachete_1/famous_stress_test_2/workspace/index.html

    The Guides from Famo.us shown using Reveal.js: –

    https://c9.io/flyingmachete_1/famous_guides/workspace/index.html

    Cheers

    Apr 21, 2014 Reply
  8. Ference

    Great posting… Was really appreciate. I would love to see some Famo.us working within Meteor samples.

    Apr 21, 2014 Reply
  9. Sharon

    Thanks Zoltan,

    I was trying to explore about famo.us and this is the perfect place to look.Great Post.

    Apr 21, 2014 Reply
  10. sekar

    Hi Zoltan! Thanks for making this post and very Interesting article. i am planning to implement famo.us in my web application(cross – platform app already deployed in android and ios). what is the pros and cons using famo.us?

    Apr 16, 2014 Reply
    • Zoltan Olah

      Awesome, good luck! I would say the main benefit of using famo.us today is that it gives you the tools to rapidly build the complex animated UI’s found in the today’s top native apps. It allows you to define your layout in javascript via the Scene Graph which in some ways is a more natural and expedient way to define a modern App’s interface.

      The main drawback today is that the framework is still very young and lacks a mature component ecosystem. In other words, you’ll be doing the work in building out the basic application components you need from the ground up.

      Hopefully, as more and more people start to use the framework, the community will build and maintain a set of high quality components that we can all re-use. Fingers crossed.

      Apr 16, 2014
  11. xiongjiabin

    hope to use it

    Apr 16, 2014 Reply
  12. metavurt

    Yup, as others have said, have you not heard of Greensock?Years, if not over a decade, of experience that the dude has, and he first built his animation engine for Flash and was used by multitudes of Flash devs, especially any that had to do banner ads, particularly those that had games contained in them. Mr. Doyle (the creator of the GSAP), then transferred the same engine to JS about 2 or 3 years ago, without a huge legal smack in the face to welcome us. So, there’s that.

    Furthermore, there is complete open source Turbolenz. Have you seen/heard of them? They went open source almost a full year ago.

    The fact that we’re all having to have a legal discussion before any of us feel comfortable downloading this and playing with it should prick famo.us’ ears….

    Apr 15, 2014 Reply
    • Zoltan Olah

      The purpose of this post is not to compare and contrast frameworks. Rather, it’s to give developers a short technical introduction to Famo.us, a UI framework that takes a considerably different approach than others.

      I’m not a lawyer and have no interest in analyzing Famo.us’ terms and conditions.

      Apr 15, 2014
    • Dominic Nguyen

      It is inevitable that developers will continue to build competing frameworks that –at their core– do similar things. Comparing the feature lists of these frameworks seems like a discussion that is impossible to resolve in one comment section.

      For the purposes of transitioning between pages and adding physics-based animations in the context of a web app, Famous seems like the right tool for the job. If we wanted 3d modeling and more game-like development features, perhaps we’d take a look at Turbulenz or GSAP.

      Apr 15, 2014
    • Barney

      Could you elaborate more on this disturbing legal stuff? Greensock is great stuff, but from the outset at least, Famous seems to have an API that’s more geared towards dealing with DOM-based UIs — rather than focussing on animation properties, it appears to offer a sensible abstraction for people who would be writing stuff with jQuery and jQuery animate enhanced — with the crucial understanding that elaborate layouts often suffer from browsers’ CSS reflow optimisation — and nerds this by managing layout internally with pure JS rather than letting the rendering engine struggle with CSS layouts.

      Apr 27, 2014
  13. Mike O'Brien

    Hi Zoltan! Thanks for making this post. Just a heads up that some of your code is using the old add/link API. We removed link so try switching those to add’s in your examples and they should work. Great post.

    Apr 14, 2014 Reply
    • Zoltan Olah

      I updated the examples – thanks for the heads up Mike, and thanks for a sweet framework!

      Apr 15, 2014
  14. John

    @Zoltan, I just read the terms and the privacy policy again and I’m still shocked by what I read, in light of where things are actually at. They want to monitor every user action, put restrictions on using their name but have full use of yours and much more, how ludicrous.

    When I first went to the site on launch day there was nothing to look at but the terms, so I could not help thinking that I had been a moth drawn to a false light and an evil contract was required before I could cross over ;-)

    At this time I am not to interested in trying to comprehend how big a ego famo.us has anymore. A quick scan of the docs already tells me what I need to know. Its render tree is very typical of object based graphic APIs, nothing new here what so ever, actually its not that robust. As far as performance in a browser goes, that is bound to work it self out within the year from numerous angles and players.

    I guess I just expected more, a better launch, better site, better samples and not to have only a big legal document shoved in my face on launch day. I’ve decided to keep going strong on my own product and just use some other canvas for round one. That should give famo.us time to bring things forward to the point where I might actually be able to feel good about accepting the terms of service.

    Apr 13, 2014 Reply
  15. Chris Gannon

    Interesting viewpoint.

    Have you looked at Greensock GSAP, in particular Draggable and ThrowPropsPlugin? If not you should because your statement ‘[ScrollView] is impossible to do without Famo.us’ is not correct. GSAP has been able to do this for a while and is a fully featured and flexible library. Just a heads up :)

    Apr 12, 2014 Reply
    • Zoltan Olah

      Chris, thanks for pointing that out. I wasn’t aware of Greensock’s Draggable plugin – it looks great too!

      Apr 12, 2014
  16. John

    The Terms of Service and other policies at the new Famo.us site seem rather demanding. Any person or company wanting to learn Famo.us has no choice it seems but to agree to their terms. Famo.us is a technology that is hardly out the door (in public beta) yet they are asking for your 100% agreement to a long list of constraints, all in their favour it seems.

    Does anyone else running a company building some unique software feel wary about the Famo.us terms? Will it hurt and limit a business or is this the norm these days? Why would such a fuss even be called for, seems rather preposterous. On the one hand their software is open source yet they want your arm and leg, or what?

    Is this something to be concerned about?

    Apr 12, 2014 Reply
    • Zoltan Olah

      I can’t imagine being attacked by famo.us’ lawyers after building a successful product on top of their framework. This would hurt everyone in the community including themselves. Is there a clause(s) in particular that you’re worried about?

      Apr 12, 2014
  17. doup

    It seems that these examples don’t work with the latest version (0.1.1), can you confirm it? I don’t have access to the docs, so maybe I’m doing something wrong.

    Apr 10, 2014 Reply
    • Zoltan Olah

      Thanks doup. I updated the examples. Great work on figuring it out as per your gist.

      Apr 11, 2014
  18. Manuel Schoebel

    Very exciting, can’t wait to test this. Thx :)

    Apr 9, 2014 Reply

Introducing Ground Control

A realtime blogging platform for Meteor

The Atmosphere Story

A brief history of the Meteor package manager