Thursday, August 11, 2016

Create a Mobile App Using Famo.us and Angular_part1

I love high-performance JavaScript, and I love sharing what I believe is its true potential. In this tutorial, I want to focus on Famo.us, which can allow you to maintain a silky-smooth 60 frames per second while having fluid animations on screen.

Famo.us does this by utilizing the CSS3 primitive -webkit-transform: matrix3d, which lets the framework compute the composite matrix and skip the browser’s renderer. No plug-in, no download, no hack. By appending this to each DIV, developers can render the composite matrix and go straight to the GPU.

I go more in-depth when discussing the ins and outs of Famo.us in this blogpost. Thanks to Zack Brown for all of his assistance with this! Let’s get started.

By the end of this project you will be able to:
  • understand how Angular works within the context of a Famo.us application
  • harness the true power of JavaScript and the good parts of HTML5
  • create smooth animations
My goal for this project is to illustrate how easily you can create HTML5 and JavaScript projects that work at near-native speeds on mobile applications.

Features
  • The mobile application runs on iOS and Android via Cordova.
  • The Windows 10 universal app runs natively on, well, Windows 10.
  • This project can also be run as a hosted website, although I have it scaled which is best for mobile devices.
Requirements
  • PC or Mac
  • Web server
  • Cross-platform test matrix (like a BrowserStack, IDE, or free virtual machines for Edge HTML, the rendering engine for Microsoft Edge and hosted web app content on Windows 10)
Setup
  1. Download the source from GitHub.
  2. Download and install a web server (I use MAMP on OS X, or the built-in IIS server with Visual Studio on Windows).
Open the Project
  1. Start your web server.
  2. Navigate to famous-angular-Pokemon/app/.
The project is designed to work on mobile devices, so use the mobile emulator in your browser to get the correct view. Here's what it would look like on an iPhone 6 inside the emulator via the Chrome desktop browser (375x667):

How It Works

Hitting the Database
I pull all of the information from the PokeAPI, which has a well-documented API, but it's missing images for each of the Pokémon. For the images, I just pull the name of the currently chosen Pokémon and append it to the end of this URL: http://img.pokemondb.net/artwork/. For example: http://img.pokemondb.net/artwork/venusaur.jpg will lead you to an image of Vanosaur. Nifty, right? Sadly, they do not have an API available.

Each time the user presses the Next button, a random number is generated between a min/max value that I've defined (say, 1 to 20), and it pulls a Pokémon from the database that matches that number. Here's what it looks like:

http://pokeapi.co/api/v1/pokemon/1/ returns a JSON object for Bulbasaur. You can play with their API.

Looping Through the Data
I then loop through that JSON object and set the properties I find to variables in Angular, using the $Scope object.

Here's an example:
  1. /*
  2.    * Grab Pokemon from the DB
  3.    */
  4.   $scope.getPokemon = function () {   
  5.     // Generate a random num and use it for the next pokemon
  6.     getRandomInt($scope.minVal, $scope.maxVal); 
  7.     // Retrieve data from DB and draw it to screen
  8.     $http.get($scope.dbURL + $scope.pokemonNum + "/")
  9.       .success(function(data) {
  10.         $scope.name       = data.name;
  11.         $scope.imageUrl   = $scope.imgDbURL + $scope.name.toLowerCase() + '.jpg'; 
  12.         /* 1) Empty out the current array to store the new items in there
  13.          * 2) Capitalize the first character for each ability from the database
  14.          * 3) Store that ability in a new abilityObj & add it into the abilities array
  15.          */
  16.         $scope.abilities.length = 0;
  17.         for (var i = 0; i < data.abilities.length; i++){
  18.          var capitalizedString = capitalizeFirstLetter(data.abilities[i].name);
  19.          var abilityObj        = {name: capitalizedString };
  20.           $scope.abilities.push(abilityObj);
  21.         }
  22.         $scope.hitPoints  = data. hp;
  23.         var firstType     = data.types[0].name;
  24.         $scope.types.name = capitalizeFirstLetter(firstType);
  25.         determineNewBgColor();
  26.       })
  27.       .error(function(status){
  28.         console.log(status);
  29.         $scope.name = "Couldn't get Pokemon from the DB";
  30.       });
  31.   };
You may notice that I also have a few other functions here, such as capitalizeFirstLetter, which does exactly that. I wanted the abilities and type (e.g. poison, grass, flying) to have the first letter capitalized, since they come back from the database in all lowercase characters.

I also loop through the abilities and push them to an ability object, which looks like this:
  1. $scope.abilities       = [
  2.   { name: "Sleep"},
  3.   { name: "Eat"  }
  4. ];
The database also returns multiple types for certain Pokémon, such as Charizard, who is flying as well as fire. To keep things simple, though, I only wanted to return one from the database.
  1. $scope.types      = { name: "Grass" }; 
  2. var firstType     = data.types[0].name;
Drawing It to the Screen
Famo.us has two waves of drawing content to the screen by creating surfaces, which are the elements that contain your text, images, etc.:
I didn't use JavaScript to draw the surfaces in this app. Instead I chose to use only FA (Famous-Angular) Directives, such as:
  1. <!-- Name-->
  2. <fa-modifier
  3.     fa-origin    ="origin.center"
  4.     fa-align     ="align.frontName"
  5.     fa-size      ="size.frontName"
  6.     fa-translate ="trans.topLayer">
  7.     <fa-surface
  8.         class    ="front-name-text">
  9.         {{name}}
  10.     </fa-surface>
  11. </fa-modifier>
This is for the name above the Pokémon on the front screen.

You'll notice that the surface is wrapped by a fa-modifier. You can read about those in the Famo.us documentation, but they essentially adjust the properties of a surface, such as alignment, size, and origin. It took me a while to wrap my head around the difference between alignment and origin, so here's how I came to understand it.

Origin 

This is the reference point on any surface. If I want to draw a rectangle and move it around the screen, I need to decide which point on that rectangle will be my starting point. The Famo.us docs explain it well. The values are laid out as follows:
  1. $scope.origin           = {
  2.                               // X    Y 
  3.  topLeft:                 [0,   0  ],
  4.  topRight:               [1,   0  ],
  5.  center:                   [0.5, 0.5],
  6.  bottomLeft:            [0,   1  ],
  7.  bottomRight:          [1,   1  ]
  8. };
Alignment

This is a surface's location on the screen. When you make changes to the alignment, it is using the origin as the reference point to start from.
  1. $scope.align              =  {
  2.                                 // X        Y 
  3.   frontName:             [0.50,    0.10],
  4.   frontImg:              [0.50,    0.40],
  5.   backImg:               [0.5,     0.38],
  6.   center:                [0.50,    0.50]
  7. };
Written by David Voyles
If you found this post interesting, follow and support us.
Suggest for you:

No comments:

Post a Comment