Interactive Generative Art Series – 01 – Color

gen-art-01-color-1gen-art-01-color-2gen-art-01-color-3
After updating the line width to be still random, but more of a gradual step in variation (in the first experiment in this series), the second most obvious edit to the original in this generative art series is the color of the line. While it would be pretty simple to update the code to use any one solid color in place of the black, I wanted the color to vary over time. The simplest way I know to achieve this is to create a variable to hold the color value (as a number) and then change it over time. So here, I have a color chosen at random and just increment it every time the loop function executes by 1024. I chose this amount because it would loop through and eventually get back to where it started while restricting the color scheme. I think it brings a lot to the design to have color – and I especially like how it randomly creates a color scheme and sticks to it. Totally random colors may look a bit much, while problematically it’s not too difficult to get, it may be difficult to look at once it’s created. Above are a few screen shots of the random colors generated:

01 Color, play here

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ replaceId=”gen-art-01″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2011/01/gen-art-01-color.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Please visit the blog article to view this interactive flash content. Flash plug-in required: Get Adobe Flash player

[/kml_flashembed]

Source Code

[cc lang=”actionscript”]
var ball:Sprite = new Sprite();

ball.graphics.beginFill(0x333333, 1);
ball.graphics.drawCircle(0, 0, 30);
ball.graphics.endFill();
addChild(ball);

var div:Number = .1;

var ax:Number = 0;
var ay:Number = 0;

var line_max_width:Number = 50;
var line_min_width:Number = 0;
var line_width:Number = Math.random() * line_max_width;
var line_width_velocity:Number = 0;
var dampen:Number = 0.95;

var color:Number = Math.floor(Math.random() * 16777215);

function loop () {
ball.x -= ax = (ax + (ball.x – mouseX) * div) * .9;
ball.y -= ay = (ay + (ball.y – mouseY) * div) * .9;

line_width_velocity += Math.random() * 6 – 3;
line_width += line_width_velocity;
line_width_velocity *= dampen;
if(line_width > line_max_width) { line_width = line_max_width; }
if (line_width < line_min_width) { line_width = line_min_width; }
this.graphics.lineStyle(line_width, color+=1024, 1);
this.graphics.lineTo(ball.x, ball.y);
}

setInterval(loop, 1000/30);
[/cc]
You’ll see if you’re following along that this only add 2 lines of code from the last version. We simply create and instantiate (with a random value) the color variable and then apply it in place of the black to the lineStyle and simultaneously increment it. Check the example swf here and get the fla here.

Interactive Generative Flash Art Series – 00 – Line Width

After seeing the source code in the original experiment, I found myself wanting to play with the code. I saw many elements of the lines and actions that could be interesting to explore. This is the first in a series, of experiments I’ll post starting from this code and pushing different things each time. They’ll start slow and simple, like this one. All I’m doing is adding a few lines of code. The first thing I wanted to see from the original was a more gradual step in the width of the line. Here are a few screenshots from this iteration:

gen-art-00-line-width-1gen-art-00-line-width-2gen-art-00-line-width-3

Play here

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ replaceId=”gen-art-00″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2011/01/gen-art-00-line-width.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Please visit the blog article to view this interactive flash content. Flash plug-in required: Get Adobe Flash player

[/kml_flashembed]

Source Code

[cc lang=”actionscript”]
var ball:Sprite = new Sprite();
ball.graphics.beginFill(0x333333, 1);
ball.graphics.drawCircle(0, 0, 30);
ball.graphics.endFill();
addChild(ball);

var div:Number = .1;
var ax:Number = 0;
var ay:Number = 0;

var line_max_width:Number = 30;
var line_min_width:Number = 0;
var line_width:Number = Math.random() * line_max_width;
var line_width_velocity:Number = 0;
var dampen:Number = 0.95;

function loop () {
ball.x -= ax = (ax + (ball.x – mouseX) * div) * .9;
ball.y -= ay = (ay + (ball.y – mouseY) * div) * .9;

line_width_velocity += Math.random() * 4 – 2;
line_width += line_width_velocity;
line_width_velocity *= dampen;
if(line_width > line_max_width) { line_width = line_max_width; }
if (line_width < line_min_width) { line_width = line_min_width; }
this.graphics.lineStyle(line_width, 0, 1);
this.graphics.lineTo(ball.x, ball.y);
}

setInterval(loop, 1000/30);
[/cc]

Method Explained

If you need a little walk through on my method to achieve this, all I did was create a variable to hold my line width, and the line width velocity (or rate of change). Every frame the line velocity grows or shrinks randomly and is applied to the line width variable. I apply a dampen to the velocity so it doesn’t get too out of hand and then set some limits to the line width. Pretty simple and it applies the same method of applying velocity to an object to make it move, but this velocity is being applied to a property of the object (width) that may not be as obvious as position. This still gives an effect of random width to the lines, but they are randomly widening and thinning, rather than just having random widths. It gives it a more fluid appearance. Any other ways you would use to achieve the same effect?

Download

Here’s the swf in action as well as the fla.

Interactive Generative Flash Art Series Intro

The world has been excited by html5/css3 recently and has been pushing limits and experimenting. It’s been exciting and funny at the same time – most of the things that are amazing people in html5 experiments have been done 5 years ago in flash. I’ve enjoyed it so much though because it has brought me back to what made me fall for flash initially: sites like levitated.net and yugop.com. People that wrote books about programming actionscript like Keith Peters, Jim Bumgardener Colin Moock, Robert Penner etc… and then art by people like Erik Natzke. I’m a geek and these guys are some of my heros (and don’t think that list is exhausted, I’ve got plenty of unmentioned flash heros), but not just because they could/can do what they do, but because they selflessly (open source-ly) taught me how to do some of it. The magic of creating something so engaging, responsive, animated, unique, random. Little experiments that feel like they contain so much life and are so lightweight -easily less than 10,240 bytes (read 10kb). I knew in high school trig and calculus that those formulas had power, but seeing it unfold and interact with it really is magical to me.

ball-natzke-1ball-natzke-2ball-natzke-3

A little inspiration

So, I’ve been toying with a lot of the things that actually taught me (or at least pushed me to learn) the basics of programming. With the years experience under my belt now I’m understanding it on a totally different level and all I want to do is find more things to make balls and lines bounce, move and swirl. And I also want to share it. Well, I recently stumbled upon a flash sneak peak video by Erik Natzke about some of his technique and then his open source files and really had some fun. Anyways I wanted to share some of the experiments that came from it. Let me know your thoughts and download the code and play with it. Let me know what else you come up with and share what you learn. I’ll start this series with a post of the original experiment from Erik on his blog here, Flash Code 101.

Natzke’s Flash Code 101

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ replaceId=”alt-ball-natzke” movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2011/01/ball-natzke.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Please visit the blog article to view this interactive flash content. Flash plug-in required: Get Adobe Flash player

[/kml_flashembed]

If it looks like greek to you, I’d suggest going to Keith Peter’s tutorials (especially the first few on gravity, easing and elasticity).

Actionscript 3

For something so fun, it’s amazing that it’s barely over a dozen lines of code.
[cc lang=”actionscript”]
var Ball:Sprite = new Sprite();
Ball.graphics.beginFill(0x333333, 1);
Ball.graphics.drawCircle(0, 0, 30);
Ball.graphics.endFill();
addChild(Ball);

var div:Number = .1;
var ax:Number = 0;
var ay:Number = 0;

function loop () {
Ball.x -= ax = (ax + (Ball.x – mouseX) * div) * .9;
Ball.y -= ay = (ay + (Ball.y – mouseY) * div) * .9;
this.graphics.lineStyle(Math.random()*10, 0, 1);
this.graphics.lineTo(Ball.x, Ball.y);
}

setInterval(loop, 1000/30);
[/cc]

Here’s the swf in action, or download the fla to play (if you really would rather download a file than copy 15 lines of code).

Resolution

Well, I’ll be playing with this code and others and posting the experiments with some screenshots of what I create get’s created.

Video Player 4 introduces interactive playlists, social sharing and more

video player 4 hero shotI’ve been busy hardening and improving my video player lately and had so many updates for it I decided to upload it to activeden as a new file altogether. After some final bug fixes and testing it’s been approved for sale. I think it’s a huge improvement over the last video player. The video playing part is mainly the same (with a few small adjustments for better usability), but I’ve added tons to this update. It’s online at activeden for live preview and purchase.

An extensively customizable yet simple video player. Create and manage play lists for you video delivery as well as allow viewers to share and socially bookmark the video. Integrate the video into your user experience with javascript integration as well as Google Analytics tracking on the video interaction! Control functionality, layout and colors of the player easily! Plus don’t sweat the embed codes – an embed code generator included!

Check out the legend graphic for some views of the player and the different panes. There is the full video view, the playlist, share and detail panes. You can also view them all in fullscreen mode.

circlecube video player 4 legend

This new player has the following updates:

  • Includes an embed script generator built specifically for this video player! Embed script generator with a Live Preview!
  • Use an external xml playlist or set playlist values in flashvars settings. (No need for xml if you don’t want it)
  • Social Bookmarking with facebook, twitter, delicious, google buzz & linkedin
  • Send emails through the player to share the video with friends
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • All colors fully customizable in flashvars or xml
  • Display video title and description – html content (may contain links) in the detail pane.
  • Video controls also in context menu (right-click menu)
  • Loop the video once, twice however many times you wish and even infinitely!
  • Disable tooltips completely if you wish
  • Keyboard shortcut integration! Press the space bar to pause/play the video just like in most video playback programs.
  • Volume setting cached across sessions for a better user experience
  • Double click video for fullscreen

As well as all that made version 3 video player great as well:

  • Supports flv, f4v and any container format using H.264: mp4, m4a, mov, mp4v, 3GP, 3G2.
  • All images and video loaded externally
  • Run this player without additional files, just pass in the flv path.
  • Supports most image file types: jpg, gif, png.
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • Load any dimension video. Completely resizable
  • Set player width and height
  • Set video width and height
  • Full screen capabilities
  • All colors fully customizable
  • Use a preview/thumbnail image.
  • Auto play option
  • Auto load option – in case you had a bunch of video on one page you wouldn’t want them all to auto load.
  • Video scale/stretching options: none, exact, uniform, fill.
  • Javascript callback functions for loading video and finishing video playback.
  • Show/hide a big play button over the video option
  • Show/hide “vcr” video player controls or have them auto-hide
  • Advanced volume controls, click to mute or drag to desired volume. Volume fades rather than cuts.
  • Support for a logo
  • Controls auto-hide
  • Time code display in current time or elapsed time. click to toggle
  • Tooltips for controls
  • Send video files to player dynamically with javascript integration (with an html link on a page send a video to play)
  • Replay video after complete
  • Progressive play and load displays. Watch as the video loads and see the scrub bar update as you watch.
  • Scrub bar is interactive click and drag. Tooltip to display hovered time.
  • Animated play controls.
  • Buttons states & tooltips.
  • All player graphics are vector shapes and very small in size.
  • Fully rearrange player controls
  • Option to disable fullscreen
  • Display video title and description – html content (may contain links)

Here’s a screenshot of the embed code generator:

embed generator preview

Access the html page URL and swf path from flash with as3

To get the url of the html page that contains the flash/swf file we need a little help from the browser. I’ve written about the following methods before, but they were in as2 with “Get current url to Flash swf using an External Interface call” and “Get Current URL and Query String Parameters to Flash in as2“. In as3, we’ll still need access to javascript in the form of ExternalInterface, so if you want to do this on a site that doesn’t allow javascript you’ll have to keep searching (or jump to the bottom for an alternative method). We don’t need to do anything with the javascript or have access to the pages source code, javascript just has to be enabled, and it works in every browser I have access to. All we do is call a javascript line from within the swf which gets the url in the browser, namely:
window.location.href
That is the javascript we need to call. But we do it from an externalInterface call like so:
ExternalInterface.call("window.location.href.toString")
or to make sure all browsers play nicely we can wrap it in a function in case the browser doesn’t want to execute that as a line, this seems to work more solidly:
ExternalInterface.call("function(){ return window.location.href.toString();}")
also note that we’re specifically applying the toString method, this is needed so the javascript actually executes something and can return it.

Other things you may want to do related to this is getting the query string variables form the url, which also uses externalInterface. You can also use this same method to get the domain, path, protocol, and even referrer. You could use some nice regex or substrings to find these from the full url, but it is already accessible. I can see a potential need for the speed to get the full url and then use internal code to cut it however I need it. But, I’m not convinced that using an external interface call takes that much time (but it’d be an interesting experiment to say the least).

You may want to find the url to the actual swf, and this doesn’t require javascript at all, the swf does know where it is even if it doesn’t know where it is embedded. We can use the loderInfo object and the url property. This returns the url to the swf file regardless of what page or even domain it is embedded on:
this.loaderInfo.url

For ExternalInterface to work in IE you need valid classid and id attributes in the tag. This is one of the reasons I use swfobject to handle my embed codes. It takes care of the Internet Exploder.

If your set up fails it may be because it throws a security error. To solve this to set the param allowScriptAccess to ‘always’ and in your actionscript add your domain, in order to enable the use of ExternalInterface.

[cc lang=”html”]

[/cc]
[cc lang=”actionscript”]
flash.system.Security.allowDomain(sourceDomain)
[/cc]

DEMO

get href url tutorial demo
This demo, gets all of the above mentioned values/properties and more. I threw in what I could think of that may be useful or interesting. It shows a couple ways to get the window location href as well as a way it won’t work. Then there are the rest of the properties available using this same method: href, host, hostname, hash (anchor link ‘#’), pathname (url after the domain), port, protocol, search (query string values), the document title and even referrer. Then from the loaderInfo object we can access the url of the swf as well as other things but most used is the bytesTotal and bytesLoaded. Now check out the demo here (adding an fpo hash and query string to the link just for demonstration purposes, feel free to play with the url and see the values updated.
[cc lang=”actionscript”]
import flash.external.ExternalInterface;

displayText.appendText(‘ExternalInterface.call(“function(){ return document.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return document.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return window.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return window.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href.toString”): ‘ + ExternalInterface.call(“window.location.href.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href”): ‘ + ExternalInterface.call(“window.location.href”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.host.toString”): ‘ + ExternalInterface.call(“window.location.host.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hostname.toString”): ‘ + ExternalInterface.call(“window.location.hostname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hash.toString”): ‘ + ExternalInterface.call(“window.location.hash.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.pathname.toString”): ‘ + ExternalInterface.call(“window.location.pathname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.port.toString”): ‘ + ExternalInterface.call(“window.location.port.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.protocol.toString”): ‘ + ExternalInterface.call(“window.location.protocol.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.search.toString”): ‘ + ExternalInterface.call(“window.location.search.toString”) + “\n”);

displayText.appendText(‘ExternalInterface.call(“function(){ return document.title;}”): ‘ + ExternalInterface.call(“function(){ return document.title;}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return document.referrer;}”): ‘ + ExternalInterface.call(“function(){ return document.referrer;}”) + “\n”);

displayText.appendText(‘this.loaderInfo.url: ‘ + this.loaderInfo.url + “\n”);
displayText.appendText(‘this.loaderInfo.bytesLoaded: ‘ + this.loaderInfo.bytesLoaded + “\n”);
displayText.appendText(‘this.loaderInfo.bytesTotal: ‘ + this.loaderInfo.bytesTotal + “\n”);
[/cc]

Finally a method I’ve used in my video players when I want users to be able to share the link through the player is send an explicit ‘permalink’ in the flashvars or xml playlist. Then the video can be embedded on any site and users can share the original video url. Plus then I don’t have to rely on javascript. I’ve written about flashvars in the past though, so I’ll leave it to you to put 2 and 2 together. Flashvars is one more plug for swfobject to me though, because it makes it so I only have to declare them once and it handles all the browser specific code.

Anyways, this demo has been tested in mac firefox, chrome, safari and windows ie7, ie8, firefox and chrome. If you have a different browser please comment that it works (or not) so we can get a full spectrum, thanks!

Download Source Files

Related tools/resources:

Actionscript (as3) Javascript Communication | Call Flash to and from javascript

Often we need to have different parts of a website talk to each other. This can get tricky when we are using multiple technologies and need the communication in real-time. Going from flash to html is done through javascript on the browser side and in actionscript we use something called ExternalInterface. The ExternalInterface class is an application programming interface that enables straightforward communication between ActionScript and the SWF container– for example, an HTML page with JavaScript or a desktop application that uses Flash Player to display a SWF file. We can send things form actionscript to javascript as well as from the html and javascript into flash and actionscript.

I’ve written about this before. It got old though and I had reports that it was having issues in certain browsers, so I had a minute to look at it and decided it needed a rebuild. This version uses as3 and swfobject. I was tempted to throw jQuery in there as well, but didn’t want to confuse anyone. This is simple javascript. I did have to throw some css3 on it for style though. I did use swfobject because it makes life easier, but it’s not required.

So, just like in as2, communication between actionscript and javascript still requires our friend ExternalInterface to link them but the setup/syntax changed a bit with as3. From the docs here are a few pointers of what we can accomplish with External Interface:

From ActionScript, you can do the following on the HTML page:

  • Call any JavaScript function.
  • Pass any number of arguments, with any names.
  • Pass various data types (Boolean, Number, String, and so on).
  • Receive a return value from the JavaScript function.

From JavaScript on the HTML page, you can:

  • Call an ActionScript function.
  • Pass arguments using standard function call notation.
  • Return a value to the JavaScript function.

It’s really cool that we can pass various data types. Here I’ve got an example that simply sends a string back and forth. We have the actionscript to javascript lane as well as the javascript to actionscript lane. So to set it up we need to know the names of our functions. Here I’ve tried to name them exactly what they are. There is a function in my javascript to both send and receive text to actionscript. Also, there are corresponding functions in my actionscript code: one to send and one to receive. These functions pass the data back and forth.

The magic is set up with the call and addCallback methods of ExternalInterface.

To call a javascript function from actionscript we use the call method. The first argument is the name of the javascript function as a String and any following (optional) arguments are the parameters that are passed to said function. So we need a function in the javascript on that page which is set up to accept some data or at least set up to do something (we don’t actually have to pass data, it could be just a trigger for something on the page). Then in our actionscript we call:
ExternalInterface.call("name_of_js_function", "data passed to js");

Then to go back from javascript to actionscript there is a little bit more set-up involved. We will use the addCallback method here and this sets the actionscript function to be able to accept a call from javascript. The first argument is the function name in javascript (again as a String), and the second argument is the function name in actionscript that you want to be called:
ExternalInterface.addCallback("name_of_js_function", name_of_as3_function);
Then you write your actionscript function to do what you want:
function name_of_as3_function():String {
//do something
return something;
}

Demo

View the actionscrip javascript communication DEMO
If that doesn’t make sense try the demo to see it in action. I’ve got the source code listed on the demo page as well as the working example.

Source Code

JavaScript

[cc lang=”javascript”]
function receiveTextFromAS3(Txt) {
document.getElementById(‘htmlText’).value = Txt;
}
function sendTextToAS3(){
var Txt = document.getElementById(‘htmlText’).value;
var flash = document.getElementById(“as3_js”);
flash.sendTextFromJS(Txt);
document.getElementById(‘htmlText’).value = “”;
}

var flashvars = {};
var params = {};
var attributes = {};
attributes.id = “as3_js”;
//attributes.name = “as3_js”;
swfobject.embedSWF(“AS3_Javascript.swf”, “alt”, “450”, “450”, “9.0.0”, false, flashvars, params, attributes);
[/cc]

HTML

[cc lang=”html”]

[/cc]

Actionscript – AS3

[cc lang=”actionscript”]
import flash.external.ExternalInterface;

//Set up Javascript to Actioscript
ExternalInterface.addCallback(“sendTextFromJS”, receiveTextFromJS);
function receiveTextFromJS(t:String):void {
theText.text = t;
}

//Actionscript to Javascript
function sendTextFromAS3(e:MouseEvent):void {
ExternalInterface.call(“receiveTextFromAS3”, theText.text);
theText.text = “”;
}
button.addEventListener(MouseEvent.CLICK, sendTextFromAS3);
button.buttonMode = true;
[/cc]

Source Files

Download the source files here:
FLA, HTML, SWF, ZIP.

Redworks

redworksI just realized that I hadn’t updated the site about it, but I’m now (since a couple months) interactive designer/developer with Redworks, subsidiary or Ogilvy & Mather in Atlanta! I’ll be doing all kinds of interactive designing and programming, specifically with flash and I’m stoked to be waist deep in Flash and as3 daily.

What? You ask is RedWorks? Well, I have been explaining it to so many that I figured I’d post this awesome video that explains it better than I ever could! Enjoy, this if from the RedWorks 3D office in NY.

Circelcube Video Player 3.0 Stock Flash Video Player at ActiveDen

hero-image

My latest stock flash video player of mine was just added to the database of stock flash items at activeDen. Go check it out and if you like it, download it for use in your projects! I’ve got lots in it for you. I’m using the principles I used as the architect for the video player for stomperNet and then at cornerstone media group in this decked out video player. Go get circlecube’s awesome stock flash video player.

circlecube-video-player-3-preview

An extensively customizable yet simple video player. Integrate the video into your user experience with javascript integration as well as Google Analytics tracking on the video interaction! Control functionality, layout and colors of the player easily! Plus don’t sweat the embed codes – an embed code generator included!

Let your video be the focus!

Features

  • Includes an embed script generator! With options for swfobject implementation or simple valid html object tags (or both)!
  • Embed generator makes setting your settings easy with a Live Preview!circlecube-video-embed-preview
  • Supports flv, f4v and any container format using H.264: mp4, m4a, mov, mp4v, 3GP, 3G2.
  • All images and video loaded externally
  • Run this player without additional files, just pass in the flv path and thumbnail path.
  • Supports most image file types: jpg, gif, png.
  • Google Analytics Integration (event tracking) – Uses on page analytics account or a specified account on a per video setting in flashvars.
    analytics-overview
  • Load any dimension video. Completely resizable
  • Set player width and height
  • Set video width and height
  • Full screen capabilities
  • All colors fully customizable in flashvars
  • Use a preview/thumbnail image.
  • Auto play option
  • Auto load option – in case you had a bunch of video on one page you wouldn’t want them all to auto load.
  • Supports Window Mode options. window, transparent, opaque
  • Video scale/stretching options: none, exact, uniform, fill.
  • Javascript callback functions for loading video and finishing video playback.
  • Show a big play button over the video
  • Show/hide “vcr” video player controls
  • Advanced volume controls, click to mute or drag to desired volume. Volume fades rather than cuts.
  • Support for a logo
  • Controls auto-hide
  • 60k file size
  • Time code display in current time or elapsed time. click to toggle
  • Tooltips for controls
  • Send video files to player dynamically (with an html link on a page send a video to play)
  • Replay video after complete
  • Progressive play and load displays. Watch as the video loads and see the scrub bar update as you watch.
  • Scrub bar is interactive click and drag. Tooltip to display hovered time.
  • Animated play controls.
  • Buttons states & tooltips.
  • All player graphics are vector shapes and very small in size.
  • Fully rearrange player controls
  • Option to disable fullscreen
  • Display video title and description – html content (may contain links)
  • Video controls also in context menu

legend-image

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. [cc lang=”html”] [/cc] 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. [cc lang=”actionscript”] this.loaderInfo.parameters [/cc] 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 0x000000 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 doesn’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: [kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/12/flashvars_as3.swf” width=”200″ height=”200″ targetclass=”flashmovie” fvars=”colors=0xFF0000,0x0FF000,0x00FF00,0x000FF0,0X0000FF,0xF0000F&delay=.66&loop=true&random=false”] Get Adobe Flash player [/kml_flashembed] And here are some more (please don’t have a seizure!) Here’s the full source if you’re interested: [cc lang=”actionscript”] /* 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); } } [/cc]

Tutorial to Create a Responsive Image Scroller in ActionScript 3.0

responsive-images-scroller-as3-thumb

I’ve written a tutorial which is published over at flash.tutsplus. This tutorial demonstrates how to create a horizontally scrolling image viewer and covers xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/07/image-scroller-example.swf” width=”550″ height=”137″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

So check out the Tutorial to Create a Responsive Image Scroller in ActionScript 3.0 over at flash.tutsplus.com!

sourcedemomilestone

You’ll find full source code available for download as well as the demo files and step by step milestones all throughout the tutorial.