Personal tools

Embedding Radi

From RadiWiki

Jump to: navigation, search

Welcome to this tutorial. I'd like to show you how to publish an animation from Radi and embed it into another web page.

Three embedding scenarios are covered:

  • Direct embedding. The Radi animation is directly placed into a web page, and it is loaded as part of the page. This is called "direct" because everything is in one HTML document, and nothing is loaded from the server by the web browser. In practice, this is simply a case of copy-and-paste into your own document, so it's compatible with everything.
  • Inline frame embedding. This uses a HTML feature called "inline frame", or iframe for short. The iframe is a standard way to display one webpage within another. It's convenient because you can leave the Radi animation in its original file, and simply refer to it from the containing page in the same way as you would load an image or a Flash animation SWF file.
  • Dynamic embedding. In this case, the Radi animation is in a separate HTML file which is loaded by the main page only when needed. This is convenient for more dynamic web applications where you may not need the content until a specific time in the app. To actually perform the dynamic loading, we'll use the popular JQuery library. (If you haven't used JQuery much, you may be surprised to see how easy this is.)

All of these have their uses. You'll get far by learning just the first two, but for more advanced web apps the ability to load Radi content dynamically can be very useful.

(By the way, if you're looking to embed an animation specifically into WordPress, there's a separate tutorial for that: Embedding Radi into WordPress)


Contents

Publishing from Radi

The animation used for this tutorial is the same one you may have seen on the Radi home page. It's called "Hokusai's horse". It contains a few sketches by the Japanese master painter Hokusai showing how to draw a horse. There is also some snow falling, which was created with a JavaScript layer. The whole thing is rendered into a Canvas element. This is a simple animation, but you could think of it as the equivalent of something like a banner ad.

See the animation here.

Note how the snow just keeps falling - the animation is running even though the timeline has completed. This is possible because the snow is rendered in code, rather than by actually animating layers on the timeline. Radi makes it very easy to mix both kinds of animations. (You can even produce videos out of programmed JavaScript animations by simply dragging the script layer into a video element.)


In this tutorial, we'll be placing this same animation into another web page. To accomplish this, we need to publish the animation from Radi in a slightly different format.

You can download the project file here:

Hokusai's horse project file


Open the project in Radi and click Publish in the toolbar at the top of the window. The following options are shown in the save dialog:

Radi v06 publish options.png


Our aim is embedding, so choose 'Fragment'.

Enter the name of the file to be saved as something that's easy to type later and doesn't contain spaces. For this example, I'll use "Horse_fragment".

We could also set the Document export name. This is not the file name, but rather the name that is used to refer to this document within a web page. For this example, let's just leave it to the suggested default, 'Hokusai_horse_in_canvas' (which Radi guessed from the project's file name).

When you click Save, you'll have a file called Horse_fragment.html. It contains the animation in a stripped form - just the JavaScript program code and the HTML elements. Next, we'll place it in a web page.


Case 1: Direct embedding

If you're familiar with HTML and you have some web page handy with which you'd like to try embedding, you can use that. If not, I've made a very simple example page.

Click here to view the example page

Download the above HTML page to your computer into the same folder as the fragment that we just published from Radi. (To download the HTML file, do a right-click or Ctrl+click on the above link, then selecting Save Link As..., Download Linked File As... or some similarly named option.)


Next, we'll edit this HTML file. Open it in a text editor. (If you don't have a preferred editor, the standard TextEdit should do. Just make sure to open and save everything as plain text instead of any rich format.)

There is a line in the file that reads like this:

<!-- place the Radi animation here -->

This is a HTML comment. Let's just do as it says.

Open the file published from Radi, "Horse_fragment.html", also in the text editor. Select all the text in the file, copy it, and paste it in the main page under the comment. (You can delete that comment line when you're done.)

Save your web page, and open it in a web browser. You should see the following:

Example page with animation embedded

(If the animation doesn't show up, something probably went wrong with the copy/paste. Try to download the original example file again. If you're not using the example file provided but your own file, then it's missing a little script. See the next chapter just below...)

The onload function

At the end of the example page used to contain this animation, you may have noticed the following piece of JavaScript:


window.onload = function() {
  var rd = Radi.documents['Hokusai_horse_in_canvas'];
  rd.renderAtFrame(0);
  rd.start();
}

This is an important bit of code -- without it, the animation wouldn't run.

What happens here is that we attach a function to the onload handler for the current browser window. When the page has been completely loaded by the browser, it calls our function.

Within the function, the first line accesses the Radi document that contains our animation. This is where we encounter the 'Document export name' that can be set when publishing from Radi. To access the document from JavaScript, this name needs to match what was published.

On the following line, the first frame of the animation is rendered: rd.renderAtFrame(0). This is necessary here to ensure that the user sees the first frame as soon as the page is loaded!

Finally, we start the animation: rd.start(). From this point on, the animation is handled completely by Radi. (We could of course still intervene using JavaScript from other parts of the same web page, if required. You could use the interface shown here to e.g. stop and then restart the animation based on user actions on the page.)


This was direct embedding, where the Radi animation is copied directly into your own web page. This is great if you want to keep everything on one page. However, if that's not necessary, there is an even easier way to place a Radi animation into your page using an iframe element.


Case 2: Inline frame embedding

This time around, we'll let the browser handle all the details of the embedding. In the containing web page, we'll create an iframe element. It's like a "document within a document": the iframe defines a box and a reference to another HTML page, and the browser loads the referred page and places it within the iframe box.

Unlike in the first case of "direct embedding", this iframe approach keeps the Radi animation and the containing page as separate HTML documents. This has both good and bad sides. The good is that it makes updating the animation really easy, because it's a separate file. The bad is that it becomes more difficult to manipulate the animation from JavaScript in the containing page. This is not a problem in practice if your needs are not very complicated. If you just need to have the animation running in its own box, the iframe is by far the easiest way to do that.

For the iframe approach, publish the animation as a complete web page rather than a fragment:

Radi v06 publish options.png

In this example, the name of the published file is "Hokusai_iframe.html".

Here is the containing web page:

Click here to view the example page

Download the above HTML page to your computer into the same folder as the "Hokusai_iframe.html" file that was published from Radi. (To download the HTML file, do a right-click or Ctrl+click on the above link, then select Save Link As..., Download Linked File As... or some similarly named option.)

Open the HTML page in a text editor. As you can see, it's very short. The embedding is achieved with a single line:

<iframe width="800" height="400" src="Hokusai_iframe.html" frameborder="0" scrolling="no"></iframe>

The attributes for the iframe tag are self-explanatory. Width and height are mandatory so that the browser can create the frame. The 'src' attribute is familiar from other HTML tags that load other files, e.g. the <img> tag used for inline images. The 'frameborder' and 'scrolling' attributes are set here so that the frame integrates tightly into the surrounding document, without any borders or scrollbars.


That's all there is to know about the iframe!

Now we've covered two different kinds of static embedding: first we copied the animation directly into a web page, and in the other approach we used the browser's inline frame functionality to load it from a separate document.

Next, we'll look at the more advanced case of dynamic embedding. This is similar to the first case of directly copying the animation fragment into the containing page, in that the animation becomes a true part of the containing document (rather than a nested iframe). But in this case, we'll load the animation content separately. This has the advantage of a smoother user experience: the containing page loads quickly, and the animation will be displayed when the dynamic load is complete.


Case 3: Dynamic embedding

A lot of websites these days use dynamic loading of content. For example, Google offers suggestions and even site previews based on what you're typing and viewing, and Facebook gives you near-realtime updates about your friends. If you're a web developer, you've probably heard the term "AJAX". It refers to this kind of asynchronous loads and updates within a web page. Using these techniques, the web page will update itself without the user navigating to another page or refreshing the browser window.

With Radi, the HTML fragment we published earlier is all ready to be dynamically loaded. We just need to set up the page that does the loading. In this example, I'll use the popular JQuery library. It offers a really convenient syntax for accessing HTML elements from JavaScript, as well as a lot of useful functions and compatibility wrappers for browser peculiarities. Any time you see a $ (dollar sign) in the JavaScript code here, that's the JQuery object -- it has been given this single-character name to make it easy to access.

Similar to the static embedding example before, download this HTML file and place it in the same folder as the file that was published from Radi:

Dynamic embedding example page

Next, you need to upload both this file and the animation file ('Horse_fragment.html') to your own web server. You can't view this dynamic loading example directly on your local computer! This is because the web browser has a very strict policy about where files can be loaded from. The content needs to be on the exact same server, or you'll get an error. Local files don't count as the same server for this policy. If you think about it, this makes a lot of sense: you certainly don't want a web page to have free access to the contents of your hard drive, even if it's a page that you've downloaded locally.

(If you don't have access to a web server or hosting provider for uploading files, you can install a local server that runs only on your computer. This is beyond the scope of this tutorial, but you can find instructions by googling.)


As it turns out, the dynamic embed is already working without any modifications by us. If you point your web browser to the file you just uploaded, it should look like this example.

Let's take a look at the source for the web page that does the loading. Here are the interesting bits:


<div id="container" style="..."></div>

Here we have an empty element with the id 'container'. This is where the animation will be loaded. (I omitted the contents of the style attribute because it's not relevant. It just sets up the container with a fixed size and some margins to make it easier to see where the border of this box is.)

The script that does the dynamic loading is just below in the file:

$(document).ready(function($){
  setTimeout(function() {
    var container = $('#container');
    
    container.load("Hokusai_fragment.html", function(response, status, xhr) {
      if (status == "error") {
        // something went wrong with the load; write an error message
        var msg = "There was an error loading the embedded Radi content: ";
        $("#error").html(msg + xhr.status + " " + xhr.statusText);
      } else {
        // ok! let's start the animation and fade it into view
        var rd = Radi.documents['Hokusai_horse_in_canvas'];
        rd.renderAtFrame(0);
        rd.start();
        container.animate({'opacity': 1}, 300);
      }
    });
  }, 2000);
});

Instead of using 'window.onload', I've switched to using the JQuery equivalent, $(document).ready(). This has advantages over using the window object directly, because JQuery knows how to handle multiple handlers for this event. (With the basic window.onload handler, if we set a function while there was another function attached to it already, it would simply get overwritten and would never run.)

Inside the function, there is a setTimeout call. This creates a timer. The call takes two arguments, a function and the number of milliseconds to wait. (In this case that value is 2000, i.e. two seconds. It's located at the end of the code, because it needs to come after the first argument which is a multi-line function here.) When the specified time has elapsed, setTimeout will call the function that we provided. Within that function, we do the dynamic loading.

The JQuery way for loading dynamic HTML content couldn't be much easier. On the first line of this function, we access the HTML element with the id 'container' that we saw above. (JQuery uses a CSS-style selector model to access elements: $('#container') finds by element id, whereas $('.container') would get all the elements that have a CSS class called 'container' applied to them. It's sometimes easy to miss the # when trying to access an element by id, so if things are not working as expected, that's one thing to check.)

Next, a method called load is called on the container element. This method takes two arguments. First is the name of the file to load -- 'Hokusai_fragment.html' in this case. The second argument is a function that gets executed when the load has completed.

Conveniently JQuery passes an argument named 'status' to this function, so that we can find out whether the load was successful or not. If it failed, status will be the string "error". The code checks for that case, and prints out the error code in a HTML element with the id error.

If the load was successful, the freshly-loaded Radi animation is started. This code is the same as in the static embedding example previously. The Radi document is accessed by name using the Radi.documents object; then its first frame is rendered; finally, the animation is started.

There's one final thing that our code does here. It calls a method called animate on the container HTML element. This method is also part of JQuery. It's a dead-simple way to do animations within a web page: simply give it the CSS properties you want to change and a duration in milliseconds, and it takes care of the rest. In this case, the animation will fade the element into view. (When the element was originally specified its opacity was set to zero, so it's invisible until the animation starts.)


That's all for this tutorial. If you have any questions or suggestions, please get in touch. My email is pauli (at) lacquer (dot) fi.


Written by Pauli Olavi Ojala, July 2011 (updated Sep 2011 for iframe embed)