Flashvars and as3

flashvars_as3_thumbFlashvars and actionscript 3! Flashvar is a way that in your html embed codes (object tags) you can send variables and values into your swf file. These variables can then be grabbed internally and used your programming! Examples of these could be images that you want to use in your swf but don’t want to import or hardcode them into the flash file or paths to xml or flv files to use as well. Actionscript 3 has a different procedure than as2 did as to how you read these flashvars from the actionscript side. The embed codes and html side of things are still the same, but in case your new to actionscript altogether, I’ll give an example of the html as well.

<object width="200" height="200" type="application/x-shockwave-flash" data="flashvars_as3.swf">
<param name="flashvars" value="colors=0x012345,0x123456,0x234567,0x345678,0x456789,0x567890,0x678901,0x789012&delay=.11&loop=true&random=false"/>
</object>

In actionscript 3 we use the loaderInfo object to access the flashvars. The parameters Object of the loaderInfo will contain all the flashvar variables and values.

this.loaderInfo.parameters

As an example of something that is visual I’ve created this little app to read some options from flashvars about colors. An app that will read a list of colors and update a box that is on the stage already to those colors with the specified delay. I always have fun with randomness so I threw in the option for random colors as well. This file looks for certain flashvars: color, loop, delay and random. These are the keys or names of the variables and they are followed by the values you want them to hold. Note that flashvars can be set in any order, so you don’t have to start with color and end with random.

In this example I’m looking for 4 flashvars specifically (in any order):

  • colors:String – a comma delimited list of hex colors or simply a string “random” for randomly generated colors (the hex for black #000000 needs to be 0×000000 in flash) (default is random)
  • loop:Boolean – whether or not to repeat these colors (default is true)
  • delay:Number – the delay between colors (in seconds). (default is 1 second)
  • random:Boolean – determines whether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false)

This is much more than is required for this example, but I was having fun playing with random colors and timing and options. I figured it diesn’t hurt to show the effect you can have with a couple different variables on one file. Here is an example using the object tags above:

Get Adobe Flash player

And here are some more (please don’t have a seizure!)

Here’s the full source if you’re interested:

/*
circlecube.com

App to demonstrate the process of getting flashvars from embed code to actionscript (as3)

Displays colors specified.

looking for 4 flashvars specifically (in any order):
colors:String - a comma delimited list of hex colors or simply a string "random" for randomly generated colors (the hex for black #000000 needs to be 0x000000) (default is random)
loop:Boolean - wether or not to repeat these colors (default is true)
delay:Number - the delay between colors (in seconds). (default is 1 second)
random:Boolean - determines wether to cycle through colors in given order or randomize. selecting random overrides the loop to true. (default is false)

*/


//initialize vars
var myflashvars:Object = new Object()
var myColors:Array = new Array("random");
var myLoop:Boolean = true;
var myDelay:Number = 1;
var randomOrder:Boolean = false;
var allRandom:Boolean = false;
//read flashvars in actionscript3
//if colors flashvars doesn't exist use these defaults
if (!this.loaderInfo.parameters.colors){
    myflashvars = {colors: "random", delay: 1};
}
else{
    myflashvars = this.loaderInfo.parameters;
}
//assign flashvars to variables within flash
for (var item:String in myflashvars) {
    trace(item + ":\t" + myflashvars[item]);
    if (item == "colors"){
        myColors = myflashvars[item].split(',');
    }
    else if(item == "loop"){
        myLoop = parseBoolean(myflashvars[item]);
    }
    else if(item == "delay"){
        myDelay = myflashvars[item];
    }
    else if(item == "random"){
        randomOrder = parseBoolean(myflashvars[item]);
    }
}

//use my variables!
if (myColors[0] == "random"){
    allRandom = true;

}
var counter:Timer = new Timer(myDelay * 1000);
counter.addEventListener(TimerEvent.TIMER, nextColor);
trace ("color number: 0", "color hex: "+myColors[0]);
setColor(myBox, myColors[0]);

counter.start();
stop();
function nextColor(e:Event):void{
    //cycle through colors
    if (!allRandom && !randomOrder){
        if (counter.currentCount+2 > myColors.length){
            if (myLoop == true || myLoop == "true"){
                counter.reset();
                counter.start();
            }
            else{
                counter.stop();
            }
        }
        trace ("color number: "+counter.currentCount, "color hex: "+myColors[counter.currentCount]);
        setColor(myBox, myColors[counter.currentCount - 1]);
    }
    //randomly select a color from the myColors array
    else if (!allRandom && randomOrder){
        var randomColor = Math.floor(Math.random() * myColors.length);
        trace ("random number: "+randomColor, "color hex: "+myColors[randomColor]);
        setColor(myBox, myColors[randomColor]);
    }
    //randomly create colors
    else{
        trace ("number: "+counter.currentCount, "color hex: "+myColors[0]);
        setColor(myBox, myColors[0]);
    }
}
function setColor(item:DisplayObject, col):void{
    if (col == "random"){
        setRandomColor(item);
    }
    else{
        setHexColor(item, col);
    }

}
function setHexColor(item:DisplayObject, col:Number):void {
    var myColor:ColorTransform  =  item.transform.colorTransform;
    //check color bounds
    if (col > 16777215) col = 16777215;
    else if (col < 0) col = 0;
    myColor.color = col;
    item.transform.colorTransform = myColor;
}
function setRandomColor(item:DisplayObject):void{
    setColor(item, (Math.floor(Math.random() * 16777215)));
}
function parseBoolean(str:String):Boolean
{
    switch(str.toLowerCase())
    {
        // Check for true values
        case "1":
        case "true":
        case "yes":
        return true;

        // Check for false values
        case "0":
        case "false":
        case "no":
        return false;

        // If all else fails cast string
        default:
        return Boolean(str);
    }
}
This entry was posted in tutorial and tagged , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

10 Comments

  1. Chris
    Posted January 25, 2010 at 12:20 pm | Permalink

    very interesting article. is there a flashvars_as3.fla file to look at?

    • Posted February 10, 2010 at 10:01 am | Permalink

      There is no fla file to download, but all it is is the actionscript included here. as I said it’s the full source. Of course to actually use it you must embed it into some html including the flashvars.

  2. Matt Brown
    Posted June 24, 2010 at 8:37 pm | Permalink

    Hey there. I am trying to use this tutorial and I get parser errors over parseBoolean. Any advice? Also had problems with myBox but figured out that I needed a box with that name in the fla.

    I am really new to AS so any suggestions would be very much appreciated.

  3. Posted July 20, 2010 at 10:05 am | Permalink

    thanks this was what i was looking for! Great stuff!

  4. ugh
    Posted July 28, 2010 at 2:43 pm | Permalink

    When you write a tutorial, write it in its simplest form. There is no way I am going to try to follow this because it is too long, and not useful for what I am trying to do. You should have written a small tutorial “How to use FlashVars”. Lay out the HTML part of it, then lay out the AS3 part of it, to pass a simple “Hello World” message. This is too complicated the way you have it now.

    • Posted August 2, 2010 at 9:26 am | Permalink

      @ugh – Well, go ahead and figure it out and write that tutorial for the community. If you’re going to go around and criticize people for not providing something to your understanding, take a minute and read the guarantee I didn’t post. Here’s a good place to start with a basic tut: http://tinyurl.com/24tbzes

  5. Posted September 2, 2010 at 1:31 pm | Permalink

    @ugh – I couldn’t disagree more. This is just what I was looking for – clear and to the point. Thanks Evan.

    • anon
      Posted May 13, 2011 at 6:21 am | Permalink

      Actually I agree with “ugh”. Tutorials should explain something in it’s simplest form. Why overcomplicate something that is so simple? While I appreciate the time people take to write tutorials (I write many myself), if your going to do something, do it right.

  6. StevieB
    Posted November 9, 2011 at 12:17 am | Permalink

    Found some FlashVar code I could just paste into my editor at http://www.justthecodeplease.com. Not as comprehensive in explaining it as this, though.

  7. olly j
    Posted December 21, 2011 at 4:55 pm | Permalink

    thanks! awesome tutorial that helped me finally get flashvars.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    WordCamp Presentation Slides: From Photoshop PSD to WordPress Theme

    Here are my slides for my WordCamp Atlanta presentation, From PSD to WordPress Theme: Under the skin: PSD to WP on Prezi Tweet

    wordpress_wordcamp_atlanta_2012_feb_2_3

    Speaker at WordCamp Atlanta 2012

    I’m proud to announce that I’ve been asked to speak at WordCamp Atlanta this year! WordCamp will be held this weekend and hosted at SCAD Atlanta! My session is titled: From PSD to WordPress Theme: Under the skin. Obviously, I’ll be focusing on themes. We’ll look at what they are, what they can do, how [...]

    Adobe-like Arrow Headers | CSS-Tricks

    Zero images is something that always gets me excited, I really like these arrow button styles! I like the css used more and the hover/active states too, nice css3 transitions. via Adobe-like Arrow Headers | CSS-Tricks. Tweet

    snow

    Snow via Javascript & Canvas – Tis the Season

    After playing with the settings in my experiments I found a few settings I liked and wanted to develop further. The first was snow! An added bonus I was able to work on a project just for the holidays and used much of this code in it! I looked around the web and saw a [...]

  • Recent Shares

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

  • Recent Comments

    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...
    Matt

    Matt

    I needed to store url variables from advertising tracking servers – this method works like a...