In flash you can have text areas that are rendered as html. You can also apply formatting styles to this html. This will show a simple example on how to apply css to html text in flash. I’ll do a simple anchor tag style to show you the ropes. We’ll style a link to be underlined and then when you hover or mouse over it, we’ll change the color. It’s a design style that is widely used online in html, but flash doesn’t natively do it. As a matter of fact, flash doesn’t even natively underline links.
Steps
Import TextField.StyleSheet
create a style sheet object: var myCSS:StyleSheet = new StyleSheet();
Specify your styles: myCSS.setStyle(“a:link”, {color:’#0000CC’,textDecoration:’underline’});
Ensure that the text box is html enabled: myHTML.htmlText = myHTMLText;
Apply the style sheet object to your html text box: myHTML.styleSheet = myCSS;
Here is some samplehtml text “+
“filling a text box this link to circlecube and example headers”+
“
Header h1
Header h2
“;
//create and initialize css
var myCSS:StyleSheet = new StyleSheet();
myCSS.setStyle(“body”, {fontSize:’15’,color:’#000066′});
myCSS.setStyle(“h1”, {fontSize:’25’,color:’#000000′});
myCSS.setStyle(“h2”, {fontSize:’19’,color:’#000000′});
myCSS.setStyle(“a:link”, {color:’#0000CC’,textDecoration:’none’});
myCSS.setStyle(“a:hover”, {color:’#0000FF’,textDecoration:’underline’});
myCSS.setStyle(“b”, {fontWeight:’bold’});
myCSS.setStyle(“em”, {fontWeight:’bold’});
//ensure html support and apply css to it
myHTML.html = true;
myHTML.styleSheet = myCSS;
myHTML.htmlText = myHTMLText;
//resize the textbox to exact fit the text in it
//myHTML.autoSize = “left”;
[/cc]
Add this to the list of things I should have already known!
Story
I’ve got an html enabled text box and was trying to devise a way that I could have a hyperlink anchor tag not link to a webpage but actually do something flash. It didn’t seem possible, and I looked through all the different html css combinations I could think of. I finally resorted to trying to use some component like Deng or FlashML. FlashML had a smaller footprint and seemed to do more what I wanted, so I started investigating it. To my dismay, the support for it was few and far between. I found an older version that came with an example file and then a newer one with some documentation but no example and I found no examples any where else. So Lee, if you ever read this, some new examples could be nice. In the documentation I was reading about a functino called AddASFunction and the example html line was very interesting:
[cc lang=”html”] link
[/cc]
I started looking through the rest of the documentation to find this asfunction use. But all it had was:
The href attribute can include the asfunction string which allows the link provided by the anchor to call a function in Flash. More of this can be found within the addASFunction definition in this help document.
I knew I was on to something, asfunction. So a quick google search and I found the official doc! I was shocked that I had the tool to do this the whole time! Well, shocked and feeling like an idiot for never having heard of it before. I knew it could be done somehow, but had no idea that it was already a feature of htmlText in flash! So now that you know my embarrassing story, I’ll let you in on the secret.
Overview
In flash, you can allow html text within a text area. You either set the text html property as true with actionscript (my_txt.html = true;) or click the ‘Render text as HTML’ button in the properties window of the text area. You cannot enable html text on static text areas however. You can have links and various html elements (but not full html). Usually links have a url in the href attribut of the anchor tag, but flash will read a special value of ‘asfunction’ which specifies that an actionscript function is to be called rather than a url. The correct syntax is asfunction followed by a colon and then the name of the actionscript function to be called, optionally followed by a comma and a possible single argument to be passed to the specified function (href=”asfunction:functionName,argument”).
Steps
Enable html in the text box.
Have your function (ex: functionName) ready to be called from the html link.
Give the href attribute of the anchor tag a property “asfunction:functionName,argument” Notice that the official documentation calls for spaces after punctuation, but any space you put after the colon (:) or comma (,) will be sent to the function in the argument, or will expect a space in the function name and give you a headache.
Example
In this example I’ve got an html enabled text box with 4 links. The first is a standard link (I hope you know what that does). The next link calls an actionscript function with asfunction. The third link sends a single argument to another function. And the last link sends multiple arguments to yet another function. Wait! Multiple arguments? I thought I said only one was supported, well this example shows how to send multiple arguments disguised as a single param and parse them. It’s pretty simple actually.
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/05/asfunction.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”375″]
myHTMLText = “Sample text in an html enabled text box. “+
“Here’s a normal link to circlecube! “+
“And some more links that don’t go anywhere, they call functions in actionscript. “+
“Click this one, “+
“to see the actionscript function called from the html text box. “+
“Click this too, “+
“and see that the actionscript function you’re calling can have an argument passed to it. And “+
“click me three and four “+
“to see a way to send multiple arguments from your htmlText. “+
“Also, one last example of what not to do “+
“Click for nothing“;
//create and initialize css
var myCSS:StyleSheet = new StyleSheet();
myCSS.setStyle(“a:link”, {color:’#0000CC’,textDecoration:’none’});
myCSS.setStyle(“a:hover”, {color:’#0000FF’,textDecoration:’underline’});
//function to be called from html text
function clickLink() {
giveFeedback(“Hyperlink clicked!”);
}
//another function to be called from html text, recieves one argument
function clickWithArg(arg) {
giveFeedback(“Hyperlink clicked! Argument: “+arg);
}
//a simple trick to allow passing of multiple arguments
function clickWithMultipleArgs(args) {
giveFeedback(“Hyperlink clicked! Multiple arguments passed: “+args);
argArray = new Array();
argArray = args.split(‘,’);
for (i = 0; i < argArray.length; i++) {
giveFeedback("arg "+i+": "+argArray[i]);
}
}function giveFeedback(str) {
trace(str);
feedback.text += str +"\n";
feedback.scroll = feedback.maxscroll;
}
[/cc]
HTML
[cc lang=”html”]
Sample text in an html enabled text box.
Here’s a normal link to circlecube!
And some more links that don’t go anywhere, they call functions in actionscript. Click this one,
to see the actionscript function called from the html text box. Click this too,
and see that the actionscript function you’re calling can have an argument passed to it. And click me three and four
to see a way to send multiple arguments from your htmlText.
Also, one last example of what not to do Click for nothing
[/cc]
I’ve had a couple special requests to explain flashvars and how to use it and show it in action.
Overview
The property “FlashVars” can be used to import root level variables to the flash movie or swf. The flashvars propery is used in codes for embedding flash in the html page. The string of variables passed in as flashvars, will be imported into the top level of the movie when it is first instantiated. Variables are created before the first frame of the SWF is played. The format of the string is a set of name=value combinations separated by ampersand (&) symbols.
Steps
Include the flashvars property in your embed codes and voila! You have these variables to use in your swf.
That’s the one step
Code
HTML Embed Codes
[cc lang=”html” tab_size=”2″ lines=”40″]
Here’s some sample embed codes, including object and embed tags:
Site built for Going Natural 3, free series of videos to promote the re-opening of StomperNet. Includes flash video and html template design in drupal all styled with custom made themes and css. Users were prompted to subscribe with email address and then allowed to view the premium video content and comment. Site discontinued, but video content still available at stomperblog.
Here’s a new site and series from StomperNet called Going Natural 3!
It’s a bit of free videos made and released to showcase the talents and business of what StomperNet is about and what they do for their clients. They’re ‘moving the freeline’ so to speak…
The first video series begins with Dan Thies talking about his ‘Crazy Theory’ for AdWords.
This site contains the latest flash video player built by yours truly. I also did the design of the site: involving html, css, php, javascript and dealing with drupal too!
I developed this game for my Digital Media Thesis. I wanted to do a project that was interactive, and enjoying flash I decided to create it in the form of a game. The project called “iKill’ is Installation Game Art, and is also available online. It explores multiple these, such as man in nature, globalization, fast food, economics, etc. The game was part of an installation for the Digital Media Exit show of Spring 2007. I kept progress of the game online at my digmeexit blog with incremental demo versions of the project. The installation had a fully interactive game and used game controller to play. In the game you play the generic man and work through the work week. Your job is to pick fruit as it grows on the trees. You receive your wages according to your harvest and at the end of the day you “cash out” and earn your happiness (how else but with Happy Meals). You do encounter obstacles and must kill the bugs before they deprive you of your happy harvest! It is pretty simple critique on a culture that equates unhealthy food to happiness without regard to the environment, and equates a mindless 40 hour work week and competitive salary to a full life. For more details visit the development blog (digmeexit.blogspot)
The Shared Object is like a cookie for flash. It lets flash store some data on the local machine, so between sessions it can remember things. Learn more from wikipedia.
Shared Objects are used to store data on the client machine in much the same way that data is stored in a cookie created through a web browser. The data can only be read by movies originating from the same domain that created the Shared Object. This is the only way Macromedia Flash Player can write data to a user’s machine. Shared Objects can not remember a user’s e-mail address or other personal information unless they willingly provide such information.
I’ve seen many Local Shared Object tutorials and examples, which have users input their name and/or hometown and other filler data. But I wanted to show how to creatively incorporate shared objects into interactions. So I’ve thrown in many simultaneous examples including the uber-simple ‘input your name and I’ll remember it’ approach. I hope I didn’t throw in so much that it got confusing… just let me know if you have any questions or anything is unclear. Keeping it simply and broad there’s only a few things to know about Shared Objects.
Steps
Simply put there are only a couple things to worry about with Local Shared Objects
Create them.
As in create the shared object
Write them.
As is write to the shared object
Set them.
As in setting variables in the shared object
Get them.
As in getting variables back out of the shared object
Clear them.
As in clearing the shared objec
Actionscript
here’s samples on how to do each of those
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
/* Create them. */
//make Local Shared Object named myLocalSO(in as) called “myflashcookie” on disk
var myLocalSO:SharedObject = SharedObject.getLocal(“myflashcookie”);
/* Write them. */
//flush the SO, write the SO to disk
myLocalSO.flush();
/* Set them. */
//set key’s value to specified value in SO
//key is the name of the data
//val is key’s value
function setVal(key, val) {
myLocalSO.data[key] = val;
trace(key +” set to “+val);
/* including writing to Shared Object in the setter function */
//flush the SO, write the SO to disk
myLocalSO.flush();
}
/* Get them. */
//get key’s value from SO
function getVal(key) {
return myLocalSO.data[key];
trace(myLocalSO.data[key] +” received from “+key);
}
/* Clear them. */
myLocalSO.clear();
[/cc]
Example
here’s my colorful example.
The purple/yellow circle is draggable, so place it where you want it. Enter your name and age in the input boxes. Press the center red ‘Set cookie’ button to copy those values to the shared object that is on your computer now. The red transparent circle represents the cookie positions. You can position the purple/yellow circle from the cookie contents with the dark green ‘Position from cookie’ button, or position it randomly with the blue ‘Position randomly’ button. Erase the cookie with the orange ‘Erase cookie’ button. Toggle easing (animation) with the Bright green button (which changes to dark red when off), it tells the current mode of ease. I have the cookie coordinates displayed and the current coordinates of the purple/yellow circle also displayed.
The cookie includes a date object, which is used to calculate the age of the cookie (watch it reset when you erase the cookie (orange button)).
The ‘All Time Visit’ stat is the only thing that does not get reset when you erase the cookie,
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/04/sharedObject.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”300″ height=”400″]
//make Local Shared Object named myLocalSO(in as) called “myflashcookie” on disk
var myLocalSO:SharedObject = SharedObject.getLocal(“myflashcookie”);
//speed var for easing
var speed = 3;
var w = myCircle._width/2;
//toggle var for easing
var ease = true;
//as var to store alltime cookie
var allTimeVisitCount=0;
countVisit();
cookieFeedback();
//line style for tracing movement
lineStyle(1, 0, 50);
//set key’s value to specified value in SO
//key is the name of the data
//val is key’s value
function setVal(key, val) {
myLocalSO.data[key] = val;
trace(key +” set to “+val);
//flush the SO, write the SO to disk
myLocalSO.flush();
}
//get key’s value from SO
function getVal(key) {
return myLocalSO.data[key];
trace(myLocalSO.data[key] +” received from “+key);
}
function countVisit() {
//if first visit
if (getVal(‘visitCount’) == undefined) {
//create date for now and store in cookie
var todayDate:Date = new Date();
setVal(‘date’, todayDate);
trace(“creating date”);
//start/reset counting visits
var visitCount = 0;
//notice allTimeVisitCount is not reset, but stored still as a var in actionscript
}
//if not easing assign coordinates from cookie
if (!ease) {
myCookie._x = getVal(‘circleX’);
myCookie._y = getVal(‘circleY’);
}
//set target to cookie coordinates
else {
ctargetx = getVal(‘circleX’);
ctargety = getVal(‘circleY’);
}
//if name then trace cookie contents
if (getVal(‘name’) != undefined) {
visitorFeedback.text = “Returning Visitor”;
nameInput.text = getVal(‘name’);
ageInput.text = getVal(‘age’);
}
//no name then a new visitor
else {
visitorFeedback.text = “First Time Visitor”;
nameInput.text = “”;
ageInput.text = “”;
}
calculateCookieAge();
}
function calculateCookieAge() {
//make a date now
todayDate = new Date();
//get the cookie’s stored date
cookieDate = getVal(‘date’);
//difference between two dates
cookieDateAge = Math.floor(todayDate – cookieDate);
//convert miliseconds to a timecode
cookieAge.text = msToTimeCode(cookieDateAge);cookieDateAge;
}
//convert miliseconds to a hh:mm:ss
function msToTimeCode(ms) {
//make sure value is within bounds. if a number grater than zero and less than the duration of video
if (isNaN(ms) || ms< 0) {
ms = 0;
}
//find seconds
var sec = ms/1000;
//find minutes
var min = Math.floor(sec/60);
//adjust seconds
sec = sec - min*60;
//find hours
var hour = Math.floor(min/60);
//adjust minutes
min = min - hour*60;
//floor seconds down to whole number
sec = Math.floor(sec);
//make time code with hours
if (hour == 0) {
if (sec < 10) {
sec = "0"+sec;
}
if (min < 10) {
min = "0"+min;
}
var tc = min+":"+sec;
}
//make time code without hours
else {
if (sec < 10) {
sec = "0"+sec;
}
if (min < 10) {
min = "0"+min;
}
var tc = hour+":"+min+":"+sec;
}
return tc;
}////// Actionscript attached to Objects/handlers ////////////place data on stage into cookie (circle coordinates and input text)
setCookieButton.onRelease = function() {
setVal('circleX', myCircle._x);
setVal('circleY', myCircle._y);
setVal('name', nameInput.text);
setVal('age', ageInput.text);
//update the display on stage
cookieFeedback();
}
//make random coordinates on stage
randomButton.onRelease = function() {
//if not easing assign coordinates to myCircle
if (!ease) {
myCircle._x = Math.random() * (Stage.width - w);
myCircle._y = Math.random() * (Stage.height - w);
}
//if easing assign coordinates to myCircle's target coords
else {
targetx = Math.random() * (Stage.width - w);
targety = Math.random() * (Stage.height - w);
}
}myCircle.onPress = function() {
this.startDrag();
dragging = true;
lineStyle(1, 200, 30);
}myCircle.onRelease = myCircle.onReleaseOutside = function() {
targetx = this._x;
targety = this._y;lineStyle(1, 0, 50);dragging = false;
this.stopDrag();
}myCircle.onEnterFrame = function() {
//print position feedback
currentx.text = this._x;
currenty.text = this._y;
//if eas move to target
if (ease) {
if (!dragging) {
moveTo(this._x+w, this._y+w);
this._x+=(targetx-this._x)/speed;
this._y+=(targety-this._y)/speed;
}
//draw line
lineTo(this._x+w, this._y+w);
}
}myCookie.onEnterFrame = function() {
//if ease move cookie to target
if (ease) {
this._x+=(ctargetx-this._x)/speed;
this._y+=(ctargety-this._y)/speed;
}
calculateCookieAge();
}//Position from Cookie
cookieButton.onRelease = function() {
//if not easing set coordinates from cookie
if (!ease) {
myCircle._x = getVal('circleX');
myCircle._y = getVal('circleY');
}
//if easing set target coordinates from cookie
else {
targetx = getVal('circleX');
targety = getVal('circleY');
}
}
easeBtn.onRelease = function () {
//toggle easing
ease = !ease;
//advance the frame of this button...
this.play();
}
clearCookieBtn.onRelease = function() {
//clear the cookie (swipe all data)
myLocalSO.clear();
//restart visit count
countVisit();
//read cookie and give feedback
cookieFeedback();
}
[/cc]
XML and flash is something that always seemed to be more complicated than it needed to be. Then I had an idea to parse the xml nodes into actionscript as objects, that would make working with xml tons easier for me, I could just parse it once and then forget about the xml, I could refer to something with the familiar dot syntax rather than worry about firstChild and nextChild and so forth…
This is for AS2. (AS3 has similar functionality built-in via E4X!)
And then I found someone who’d already done that with XML2Object.as, here it is:
Here is my example file. But since you cant really see Objects in the code on the stage, I’ve included a recursive trace function to loop through the object and print the data.
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import XML2Object;
function recurseTrace(info:Object, indent:String) {
for (var i in info) {
if (info[i] == null){}
else if (typeof info[i] == “object”) {
myTrace(indent + i + ” -“);
recurseTrace(info[i], indent);
}
else {
myTrace(indent + i + ” = ” + info[i] +”, “);
}
}
}
function myTrace(myLine:String){
feedback.text += “|”+myLine;
trace(myLine);
}
[/cc]
And here’s my sample xml file: (it’s the same one I use in my Dynamic Flash Scrolling Link List files)
[cc lang=”xml” tab_size=”2″ lines=”40″] 3D https://circlecube.com/circlecube/tag/3d/