Sencha Inc. | HTML5 Apps

Blog

Create a Small Interactive Application with Sencha Animator

February 29, 2012 | Arne Bech

Create a Small Interactive Application with Sencha Animator
This tutorial will show you how to create a small, interactive app with Sencha Animator.

Sencha Animator is very flexible, and it can be used for a variety of purposes, from prototyping mobile applications to creating interactive animated features for iBooks. This tutorial shows how an animation can quickly be enhanced to an interactive mini-app by adding actions and custom code.

Download Sencha Animator  Download Project Files   View Animator Docs

Before you get started

To successfully complete this tutorial, you will need to be familiar with Animator. Before getting started, it’s a good idea to have absorbed the basics:

  • Download and install the latest Sencha Animator.
  • Review Animator documentation and follow the Animator Quickstart tutorial.
  • Download project files and resources. They include a partially built “before” version, startQuiz.animproj, which you can open in Animator and use during the tutorial so we can focus on adding interactivity, logic, and JavaScript code. Also included is an “after” version, finishedQuiz.animproj, which shows the finished project after completing the steps described in this tutorial.
  • Have a WebKit browser like Google Chrome or Apple Safari to preview your Animator projects. (You can also use the iOS Simulator included with Xcode for Mac OS X.)

Open the project

Open startQuiz.animproj in Sencha Animator. In the Scenes Panel, you should see five scenes, as follows:

  1. Intro
  2. Questions
  3. Incorrect
  4. Correct
  5. Score

Select and run each scene to see what it does. You should also select the elements in each scene to familiarize yourself with them before we start adding interactivity. As you select elements, keep in mind that Animator lets you select an object on the Center Stage in two ways:

  • Base state mode. When you select an object that’s not on a keyframe, Animator displays it inside a purple box in the Center Stage. To view an object in this mode, click its name in the Object Tree or click the object in the timeline in between keyframes. Selecting an object in base state mode means you can edit its base properties, which persist with the object throughout the scene.
  • Keyframe mode. When you select an object currently on a keyframe, Animator displays it inside a blue box in the Center Stage. To view an object in this mode, click on a keyframe in the Object Tree. Selecting an object in keyframe mode means you can edit its keyframe properties, which can change when the object reaches the next keyframe.

In the File menu, select “Preview Project in Browser” to view the project in the browser. You’ll see the first scene, which doesn’t allow for any user interaction yet. We’ll take care of that in the tutorial by adding actions and a little JavaScript code to each scene. In the process, we’ll turn the project into a generic interactive quiz template.

Code view in Sencha Animator
Code view in Sencha Animator. (Click to view.)

Scene 1: Intro

Select Scene 1 in the Scenes Panel, and select the element called Button in the Object Tree. You can also select it in the Center Stage — it contains the text “Start”. In the Property Panel, in the Click action property under General, select “Go to next scene”. When the user clicks the button in the running animation, it will now advance to the next scene. Go ahead and try this by saving your project and selecting Preview Project in the File menu. (Be sure to save your project from time to time after this.)

Let’s also add some JavaScript to initialize a new set of quiz questions. Be sure the Intro scene is selected in the Scene panel, and in the Property Panel set the Start property under Actions to Custom JavaScript. Click Open editor and paste the following code into the Custom JS window:

// Create a global object/namespace for the project to use.
if (typeof(quizData) === "undefined") {
    quizData = {};
}
 
// To help work with scenes, translate some
// scene ids into names. The scene id can be found
// by hovering the mouse over a scene in the Scene Panel. 
if (!quizData.sceneIDs) {
    quizData.sceneIDs = {
        question: 1,
        wrong: 2,
        correct: 3,
        score: 4
    };
}
 
// Set up some questions.
if (!quizData.questions) {
 
    // Each question text entry consists of a question, 4 answers,
    // and the index of the correct answer.
 
    quizData.questions = [
        {
            question: "Which one of these is a CSS3 property?",
            answers: [
                'animation-degradation',
                'animation-path',
                'animation-fill-mode',
                'animation-speed'
            ],
            correctAnswerIndex: 2
        },
        {
            question: "What is the syntax to start a keyframe segment in CSS3?",
            answers: [
                "@keyframes 'name'",
                "@animation 'name'",
                ".element:animation",
                ".element:keyframes"
            ],
            correctAnswerIndex: 0
        },
        {
            question: "Which is a valid CSS3 animation-timing-function?",
            answers: [
                'slide-in',
                'ease-out',
                'jump-out',
                'fast-in'
            ],
            correctAnswerIndex: 1
        }  
    ];
 
}
 
// Set up or reset variable for the current question.
quizData.currentQuestionIndex = -1;
 
// Set up or reset variables to keep track of score.
quizData.scoreRight = 0;
quizData.scoreWrong = 0;

Read through the code comments so you can see what each section does. Close the Custom JS window and save the project.

Scene 2: Questions

Select the Questions scene in the Scenes Panel, then select the Question text element in the Object Tree. In the Properties Panel set General->CSS ID to question. This will give the DOM element an ID of question in the exported code so it can easily be referred to from JavaScript code. Similarly, set the CSS IDs of the four buttons (from top to bottom in the Object Tree) to button1 (top-most), button2, button3, and button4. Note that Animator will not let you assign the same CSS ID to two elements; Animator automatically changes any redundant name.

Be sure the scene is still selected in the Scenes Panel, and in the Properties Panel, under Actions, se the Start property to Custom Javascript and add the following code, again being sure to review the comments so you can see what each section does:

// Increment the question index.
var index = ++quizData.currentQuestionIndex;
 
// If there are no more questions, go to the Score scene.
if (index >= quizData.questions.length) {
    controller.startSceneByID(quizData.sceneIDs.score);
    return;
}
 
// Get the current question.
var currentQuestion = quizData.questions[index];
 
// Get references to the different elements on the stage;
// notice that the text we want to edit resides inside
// span elements.
var question = document.querySelector('#question span');
var button1 = document.querySelector('#button1 span');
var button2 = document.querySelector('#button2 span');
var button3 = document.querySelector('#button3 span');
var button4 = document.querySelector('#button4 span');
 
// Update the question text.
question.innerHTML = currentQuestion.question;
 
// Update buttons and answers.
button1.innerHTML = currentQuestion.answers[0];
button2.innerHTML = currentQuestion.answers[1];
button3.innerHTML = currentQuestion.answers[2];
button4.innerHTML = currentQuestion.answers[3];
 
// Store the correct answer index.
quizData.correctAnswerIndex = currentQuestion.correctAnswerIndex;

Preview the project again, and you should see that the questions and answers have been updated.

Next, add logic to each of the objects labelled Button to detect if an answer is correct. One at a time for each button, in the Properties Panel select the Custom JavaScript in the Click action property under General, and the following JavaScript, setting buttonIndex in each Button (from top to bottom in the Object Tree) to 0, 1, 2, and 3:

// Check if this is the button with the correct answer.
var buttonIndex = 0;
if (quizData.correctAnswerIndex === buttonIndex) {
    controller.startSceneByID(quizData.sceneIDs.correct);
} else {
    controller.startSceneByID(quizData.sceneIDs.wrong);
}

Preview your app in a WebKit browser
Preview your app in a WebKit browser.

Scene 3: Incorrect

Select the Incorrect scene in the Scenes Panel, then select the Answer text element (which contains the text “Texas” in the Content field under General in the Properties Panel) in the Object Tree. Set the CSS ID for the Answer element to correct-answer. Then set the start action of the scene to Custom JavaScript and insert the following code:

// Get the current question.
var question = quizData.questions[quizData.currentQuestionIndex];
 
// Get the element that displays the correct answer.
var correctElement = document.querySelector('#correct-answer span');
 
// Update the answer.
correctElement.innerHTML = question.answers[question.correctAnswerIndex];
 
// Increase the wrong answer score.
quizData.scoreWrong++;

Set the click action for the object called Button (which displays the text “Continue”) to Go to Scene and select “2. Questions”.

Scene 4: Correct

Select the Correct scene in the Scenes Panel, set the start action of the scene to Custom JavaScript, and insert the following code in the Custom JS window:

// Increment the correct score.
quizData.scoreRight++;

Select the Button element in the Object Tree, set its Click action property to Go to scene, and select 2. Questions. You may have to open the disclosure triangle next to the Click action property to view the list of scenes.

Scene 5: Score

Select the Score scene in the Scenes Panel, then select the Score element in the Object Tree. Set its CSS ID to final-score. Then set the start action of the scene to Custom JavaScript and insert the following code to the Custom JS window:

// Get element for score.
var scoreElement = document.querySelector('#final-score span');
 
// Get score and total possible points.
var right = quizData.scoreRight;
var total = quizData.scoreRight + quizData.scoreWrong;
 
// Create score text.
var text = right + '/' + total + ' points';
 
// Display score text.
scoreElement.innerHTML = text;

Finally, set the Click action property for the scene’s Button element to Go to scene and select “1. Intro”.

Finishing Touches

To make this display well on an iPhone, we need to add meta tags to make the app occupy the full screen and so it can be easily saved as a web app on the Home screen. Note that the dimensions set for the app are optimized for full screen mode. We also add a couple of lines of JavaScript to hide the address bar when the page loads.

To do that, select the Project tab, click the Head HTML field under Export, and enter the following code:

<meta name="viewport" content="user-scalable=no, width=device-width">
<meta name="apple-mobile-web-app-capable" content="yes">
<script type="text/javascript">
// hide the address bar
window.addEventListener("load",function() {
    setTimeout(function(){
        window.scrollTo(0, 1);
    }, 0);
});
</script>

Load your Sencha Animator app in the iOS Simulator
Load your Sencha Animator app in the iOS Simulator.

Deploy the App

Now that the project is complete, select Export in the File menu to create a directory containing an HTML file for the project and its image assets. You can put this directory on your web server to host the quiz mini-app. Here is a link to a hosted version of the app. If you have access to an iPhone or the iOS Simulator, save the app to your home screen and see how it works!

Conclusion and Next Steps

This guide has shown you how to add actions and custom code to create rich interactive animations that can be combined into a mini-app with little effort.

Since the mini-app is based on open standards it can easily be extended. It could be wrapped for native and submitted to the App Store. Instead of using hard-wired content, the app could get questions and answers through a JSON request. It could be integrated with Sencha.io to provide scoreboard functionality and much more.

If you expand this application, go ahead and show us your work by creating a new thread in the Sencha Animator forum.

There are 5 responses. Add yours.

Dinesh M

3 years ago

Hi,this is good

Dinesh M

3 years ago

great!!!!!!!!

tom eloph

3 years ago

whenever i try to load any of the code examples, Animator throws an error and i can’t open the project… help please

narcis

3 years ago

very nice of you to share this, but it’s very complicated.

NOC

2 years ago

Great it’s Allow us to show creativity.

Comments are Gravatar enabled. Your email address will not be shown.

Commenting is not available in this channel entry.