Fullscreen in AS3 Tutorial | Plus Firefox Flash bug when enter fullscreen keyboard events fired

To view the full fullscreen tutorial go here: How to use fullscreen in AS3 | Stage Display State Tutorial

fullscreen_keyboard_bug_thumbnail
Sucks when you seem to have a bug in your code somewhere so you dissect your code over and over and are convinced that according to your code, everything should be fine, so you come back later thinking fresher eyes will see it, and still can’t find the cause, and then resort to debugging with various trace statements…

I’ve been developing a custom flash player in as3. Fullscreen and all those bells and whistles… I could test locally and eveything was beautiful… but then upload and test in the browser and when I would go into fullscreen mode, the video would pause. Pretty annoying bug! So I’d go through my code and examine anywhere a call to pause the video (there are only two): pressing the play/pause button and pressing the spacebar (keyboard shortcut). I couldn’t find any correalation. I was thinking adobe must be doing some crazy security things when going into fullscreen… but no, no other video player I’ve seen does this!
After commenting out my keyboard events, the bug is fixed! But I still can’t use the spacebar to pause/play. I love this functionality for usability. Isn’t that pretty standard for video? space to pause, it’s like second nature to me.

Does entering fullscreen really trigger a keyboard event equivalent to pressing my spacebar!? Sure enough. how much sense does that make, but it gets better! I had a friend test this swf and it worked fine for him. No pause on fullscreen! Wha!? Using good ole IE7… So yes, it’s a browser specific actionscript bug, firefox even! That was one of the things I liked about flash initially, not too much to mess with as far as cross browser issues once you get the swf embedded in the html, or so I thought.

So after playing with booleans to try to control when the keyboard events will be working.

Has anyone experienced this or another issue that just left you baffled, even after you figured out the bug?!

Well, I’ve done the right thing, I’ve posted about it to hopefully help anyone else having this issue. I created a test case file to rule out anything else in my code and make sure I’m not crazy.
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/03/fullscreen_keyboardevent_bug.swf” targetclass=”flashmovie” bgcolor=”#336666″ publishmethod=”dynamic” width=”550″ height=”400″ allowfullscreen=”true”]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript”]
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

fsb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
ssb.addEventListener(MouseEvent.CLICK, fullscreenToggle);
stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreenChange);
fsb.buttonMode = true;
ssb.buttonMode = true;
onFullscreenChange();

function fullscreenToggle(e:MouseEvent = null):void {
//normal mode, enter fullscreen mode
if (stage.displayState == StageDisplayState.NORMAL){
//set stage display state
stage.displayState = StageDisplayState.FULL_SCREEN;
}
//fullscreen mode, enter normal mode
else if (stage.displayState == StageDisplayState.FULL_SCREEN){
//set stage display state
stage.displayState = StageDisplayState.NORMAL;
}
onFullscreenChange();
}
function onFullscreenChange(e:FullScreenEvent = null):void {
if (stage.displayState == StageDisplayState.FULL_SCREEN) {
tracer(“full screen”);
fsb.visible = false;
ssb.visible = true;
}
else {
tracer(“small screen”);
fsb.visible = true;
ssb.visible = false;
}
tracer(“toggle to “+stage.displayState);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);

function keyDownListener(e:KeyboardEvent) {
tracer(“keyboard: keyCode: “+ e.keyCode.toString());
}
var tracerwindow:TextField;
function tracer( …args){
if (tracerwindow == null){
tracerwindow = new TextField();
tracerwindow.width = stage.stageWidth/2;
tracerwindow.height = stage.stageHeight;
tracerwindow.multiline = true;
addChild(tracerwindow);
}

for (var i:uint = 0; i < args.length; i++) { tracerwindow.appendText(args[i].toString() + " "); } tracerwindow.appendText("\n"); trace(args); } [/cc]other places that I've found this mentioned that helped me understand what was going on: http://dreamweaverforum.info/actionscript-3/123202-keyboard-event-full-screen.html http://bugs.adobe.com/jira/browse/FP-814

Random Movement | Brownian revisited for as3

I have had feedback that certain random movements I program are a bit “jumpy”. Such as my old brownian movement tutorial and I really noticed it in my last tutorial, the parallax 3d depth effect tutorial. I’ve been thinking about it and looking around at some code and now have this updated brownian movement example! Updated for as3 as well as making it less jumpy.

as3brownian thumb pngFirst I’ll explain what I’ve found to be the reason of the jumpiness. And then explain and show what can be done to make this movement be more smooth.

So to examine the old jumpy code. Jump back to the first version post here. I think my technique was well thought out here, but the application was poor. It was recalculating the velocities every single frame and then incrementing the coordinate positions by the newly calculated velocities… This is where the jumpiness comes in. Even though the random value was named velocity, it didn’t actually affect the dot’s velocity, it was just a variable that stored the random value used to move the current x/y coordinates.
To help the animation be more smooth, the velocity needs to be more smooth. The velocity, rather than calculating it fresh each frame, should be randomly modified each frame. And then the new velocity will calculate the new ‘random’ position. Another addition is to introduce another force to dampen the velocity over time, so things don’t get too crazy…

Steps:

  1. Modify velocity randomly
  2. With velocity and current position, calculate a new position
  3. Dampen the velocity

Example:

Here I have a velocity for the x coordinate as well as the y. I’m also experimenting with a z velocity. This adjusts the alpha and scale for depth perception. It doesn’t actually edit the depth or layer the dot shows up on the stage however… keyword here: experimenting. 🙂
[kml_flashembed fversion=”8.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/02/as3random_brownian_movement.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”550″ wmode=”transparent”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript:

[cc lang=”actionscript”]
//number of balls
var numBalls:uint = 50;
var defaultBallSize:uint = 30;

//init
makeDots();

function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum stage.stageWidth) {
thisBall.x = 0 – thisBall.width;
}
else if(thisBall.x < 0 - thisBall.width) { thisBall.x = stage.stageWidth; } if(thisBall.y > stage.stageHeight) {
thisBall.y = 0 – thisBall.height;
}
else if(thisBall.y < 0 - thisBall.height) { thisBall.y = stage.stageHeight; }if (thisBall.scaleX > maxScale){
thisBall.scaleX = thisBall.scaleY = maxScale;
}
else if (thisBall.scaleX < minScale){ thisBall.scaleX = thisBall.scaleY = minScale; } if (thisBall.alpha > maxAlpha){
thisBall.alpha = maxAlpha;
}
else if (thisBall.alpha < minAlpha){ thisBall.alpha = minAlpha; } }function randomColor():Number{ return Math.floor(Math.random() * 16777215); } [/cc]

Source:

as3random_brownian_movement.fla

Foundation Actionscript 3.0 Animation: Making Things Move! | Review

as3animation coverKeith Peter‘s Foundation Actionscript 3.0 Animation: Making Things Move!

Can I just say WOW! Being a student of art and animation before turning to the flash world, I love how Keith is able to explain programming in terms that are very easy to understand and follow. I’ve been a huge fan of his since I first peeked at Flash Math Creativity and Flash Math Creativity, Second Edition. I then followed to his bit-101 site and devoured his tutorials there: gravity, easing, elasticity, etc…

This book helps me transition all those techniques I’ve incorporated into my practices from actionscript 2 to actionscript 3. He also teaches me more about object oriented programming with the same simplicity he explained gravity years ago. It’s a great read and an essential part of my collection. I could safely say that I’ve learned more (at least as much as) from Keith’s work than anyone else in the industry. Anything from him always make sense and inspires my code and projects to be better. So go get his book to support him!

Also, friends of ed makes available the source code that goes with the text here.

Thanks Keith — and keep up the great work!

How to as3 resize a movieClip and constrain proportions | Actionscript Tutorial

constrain proportions jpgI’ve had that exact task numerous time while scripting actionscript. I have a source image loaded externally or a mc within the program and I need to fit it into a certain area (width x height) but keep the aspect ratio the same or as photoshop calls it “constrain proportions”. I’ve done this with fancy and not so fancy formulas and equations, but finally I had it and created a simple function that would do it every time. Figured it was worth sharing cause if I’ve googled it before then others most likely will too!

This is more than just setting the width and height of an object, because that way the image is easily skewed and the natural proportions are messed up. If you want to just use scale you need to know the dimensions of the image being resized, and that’s just not scalable (no pun intended).

What we have to do is to do both. Assign the width and height to skew it, and then scale it to correct the proportion. So if we want to resize an image when we don’t know it’s current size to fit into a 300 pixel square we set the width and height of that image to 300 and then a bit of logic that can be summed up in one line:
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
That says if the x scale is larger than the y scale set the x to the y scale amount, and vice versa. It's basically setting both scales to the smaller of the two. This works because we don't know the original size of the image, but actionscript does. scaleX and scaleY are ratios of the current width and height to the originals. A little complicated I know, but that's why I've made the function below. I know how to use it and now I don't have to think about skewing and then scaling back to keep my aspect ratio or proportion. You should see how to use it just by looking at it:
resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true)
Pass in the movieClip you want to resize, and the size you want it to fit into. So with the same example above, just do
resizeMe(image, 300);

Example

Here's an interactive example to show what I mean. It loads an external image and you click and drag the mouse around to resize it. To toggle whether you want to constrain proportions use the space bar. Type a url to any image you want to test it with and press load, or hit 'enter'.
[kml_flashembed fversion="9.0.0" movie="https://circlecube.com/circlecube/wp-content/uploads/sites/10/2009/01/constrainproportions.swf" publishmethod="dynamic" width="550" height="550"]

Get Adobe Flash player

[/kml_flashembed]

Here's a screenshot of me playing with a photo in here NOT constraining proportions.
constrain proportions jpg

Source (AS3)

The resizing function
[cc lang="actionscript"]
//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{
maxH = maxH == 0 ? maxW : maxH;
mc.width = maxW;
mc.height = maxH;
if (constrainProportions) {
mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; } } [/cc]The full source [cc lang="actionscript"] var defaultUrl:String = "https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/circlecubelogo4.png"; var image:MovieClip = new MovieClip(); loadImage(); function loadImage(url:String=""):void { if (url == "" || url == defaultToLoadString) url = defaultUrl; //clear image image.visible = false; image = new MovieClip(); //add image var ldr:Loader = new Loader(); var urlReq:URLRequest = new URLRequest(url); trace("loading image: " + url); ldr.load(urlReq); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imageCompleteHandler); image.addChild(ldr); addChild(image); }function imageCompleteHandler(e:Event):void { resizeMe(image, stage.stageWidth) }//The resizing function // parameters // required: mc = the movieClip to resize // required: maxW = either the size of the box to resize to, or just the maximum desired width // optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once) // optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true. function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{ maxH = maxH == 0 ? maxW : maxH; mc.width = maxW; mc.height = maxH; if (constrainProportions) { mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; } }var constrainOn:Boolean = true; var isPressed:Boolean = false;stage.addEventListener(MouseEvent.MOUSE_MOVE, moved); stage.addEventListener(MouseEvent.MOUSE_DOWN, pressed); stage.addEventListener(MouseEvent.MOUSE_UP, released); stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);function keyDownListener(e:KeyboardEvent) { if (e.keyCode == 32){//spacebar toggled(e); } if(e.keyCode == 13){//enter loadImagePress(e); } }function moved(e:Event):void{ if (isPressed) resizeMe(image, mouseX, mouseY, constrainOn); } function pressed(e:MouseEvent):void{ isPressed = true; moved(e); } function released(e:MouseEvent):void{ isPressed = false; } function toggled(e:Event):void{ constrainOn = !constrainOn; moved(e); } var defaultToLoadString:String = "type url of image to load"; toLoad.text = defaultToLoadString; toLoad.addEventListener(FocusEvent.FOCUS_IN, toLoadFocus); toLoad.addEventListener(FocusEvent.FOCUS_OUT, toLoadBlur); function toLoadFocus(e:FocusEvent):void{ if (toLoad.text == defaultToLoadString) toLoad.text = ""; } function toLoadBlur(e:FocusEvent):void{ if (toLoad.text == "") toLoad.text = defaultToLoadString; } loadBtn.addEventListener(MouseEvent.CLICK, loadImagePress); function loadImagePress(e:Event):void{ loadImage(toLoad.text); } [/cc]

Download

constrainProportions.fla

And as usual, let me know if you've got any comments questions or suggestions! Thanks,

asfunction (TextEvent.LINK) Tutorial for AS3 | Flash HTML Link to call actionscript function | Tutorial

Overview

Earlier I wrote a tutorial article about asfunction in as2. Now that I’ m into as3, surprise surprise asfunction has been depreciated and now to replace it is the LINK TextEvent. Dispatched when a user clicks a hyperlink in an HTML-enabled text field, where the URL begins with “event:”. The remainder of the URL after “event:” will be placed in the text property of the LINK event.
This differs from the asfunction method in that we must add an event listener (addEventListener) to the textField object, the event listener specifies which function will be called in the event of a link click and there is no way to send arguments along with the event (AFAIK). But it’s easy enought to use one link event function for all your link events and put in a simple switch statement to coordinate the desired results…

Steps

  1. Use event in the href attribute. (href=”event:eventText”)
  2. Listen to the textField (theTextField.addEventListener(TextEvent.LINK, linkHandler);)
  3. Handle the link event (function linkHandler(linkEvent:TextEvent):void {…)

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/12/textlinkevent_as3.swf” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

[cc lang=”actionscript”]
var myHTMLText:String = “Sample text in an html enabled text box.\n”+
“Here’s a normal link to circlecube putting the link into the href attribute like normal!\n”+
Click this circlecube, to see the text event link in action! \n”+
“And some more links that don’t go anywhere, but they do call functions in actionscript. “+
“Click this to move UP, click me move back “+
DOWN.\n”+
“Also, one last example click for a trace test“;

//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’});
myHTML.styleSheet = myCSS;
myHTML.htmlText = myHTMLText;

myHTML.addEventListener(TextEvent.LINK, linkHandler);

function linkHandler(linkEvent:TextEvent):void {
switch (linkEvent.text) {
case “clickLink”:
clickLink();
break;
case “moveUp”:
moveUp();
break;
case “moveDown”:
moveDown();
break;
default:
giveFeedback(linkEvent.text);
}
}
//function to be called from html text
function clickLink():void {
giveFeedback(“Hyperlink clicked!”);
var myURL:String = “https://circlecube.com/circlecube”;
var myRequest:URLRequest = new URLRequest(myURL);
try {
navigateToURL(myRequest);
}
catch (e:Error) {
// handle error here
giveFeedback(e);
}
}

//another function to be called from html text, recieves one argument
function moveUp():void {
feedback.y -= 10;
giveFeedback(“Up”);
}

//a simple trick to allow passing of multiple arguments
function moveDown():void {
feedback.y += 10;
giveFeedback(“Down”);
}

function giveFeedback(str):void {
trace(str);
feedback.appendText(str +”\n”);
feedback.scrollV = feedback.maxScrollV;
}
[/cc]

Source

Download the fla here: textlinkevent_as3.fla

StomperNet Strikes Again! with FormulaFIVE

StomperNet has been a ‘buzz’.

After Andy’s ‘Mea Culpa‘ why wouldn’t it be…

But this is so much better and bigger, learning many lessons from the last launch – StomperNet strikes again!

Teamed up with Paul Lemberg a new product called FormulaFIVE (F5 for short).

Just launched a video to excite the industry!
So check out stomperf5.com now!

formula five landing page

Learning ActionScript 3.0: A Beginner's Guide | Book Review

Rich Shupe and Zevan Rosser’s Learning ActionScript 3.0: A Beginner’s Guide.

This book is published by O’Reilly and is part of the Adobe Developer Library.

This book was a great way for me to move into as3. I’m coming from a visual design background with little formal programming training, to know more of my background check my about page. Being mostly self taught, I found myself learning about basic programming skills with this book. This book helped me catch up to the as3 world and I began doing some really cool things in flash once I had a base for understanding all the differences and new things in as3.

I really enjoyed the visual aspects of this book as well. Many of the diagrams and illustrations have the hand drawn look. Like so:




I would recommend this book to anyone who wants to better understand actionscript and actionscrip3 more specifically. It’s a great helper at migrating from as2 to as3. On the cover, it claims to teach “everything needed for non-traditional programmers–web designers, GUI-based Flash developers, those new to Actionscript, visual learners–to understand how Actionscript works and how to use it in everyday projects.” I would agree with that whole-heartedly. All I can say is that after reading it and working through some of the samples included, I better understand AS3 and am confident that through the foundation it has helped me lay I will soon become an actionscript ninja.

Thanks Ryan and Zevan!

Preloader Stats File @ FlashDen

A preloader bar that gives full stats, speed, kb, and even remaining download time!

[kml_flashembed fversion=”9.0.0″ movie=”http://activeden.net/files/58667/preview.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”280″]

Get Adobe Flash player

[/kml_flashembed]

Preloader with Stats

Clean slick preloader. Rounded bar with gradient fill and bevel and glow filter. All actionscript driven, no animations to bloat file size. Rounded corners don’t distort as width changes.

Includes loading statistics for download.

Calculates the following:

  • Percent Loaded
  • Loaded kilobytes
  • Total kilobytes
  • Average kilobytes per second download speed
  • Remaining dowload time in seconds
  • Gives kilobytes to 2 decimal places without dropping zero’s

To Use:

Easy to use, just paste in frame 1 of your file. (actionscript code included!)

Customize:

Customize color easily. Edit the fill color of the preloader_bar movie clip in the library.

Customize font easily. Edit the font for the text box named feedback on the text layer of the preloader mc.

Circlecube Flash Items at activeden

21075 24687 45713 45893 22018

Detect Flash Player Version | Actionscript based detection method (as3)

See my previous post about how to do this with as2: Detect Flash Player Version | Actionscript based detection method (as2)

Overview

Recently I had a requirement that I had to detect which version of the flash player was currently installed. This is a normal thing, we do it all the time when embedding flash into html, we detect which version of the player is installed and if the user has an old version they are invited to upgrade…

But what about finding the flash version from within flash? An actionscript based detection method? I hadn’t ever thought about doing that…

Actionscript 3 now uses the flash system capabilities class to report all it’s “capabilities”. First we have to import it and then we have access to all the details through the Capabilities object, such as operating system, language, pixel aspect ration and flash player version. There are a ton of others and I’ve included them in the trace statements.

Steps

  1. import the class import flash.system.Capabilities;
  2. read the version from the Capabilities object var flashPlayerVersion:String = Capabilities.version;

This returns a string, 3 letter operating system, a space, and then the version number as four numbers seperated with commas. (just like eval(‘$version’); in as2)
I display the flashPlayerVersion and to split it out I split the string on the space, and then split the version number with the comma delimiter and display them all.

Example

Here’s what mine is (gif):

flash player version detection as3

And here’s what yours is (swf):
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/flashversiondetectionactionscriptmethodas3.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”160″ height=”160″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript (as3)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.system.Capabilities;

var flashPlayerVersion:String = Capabilities.version;

var osArray:Array = flashPlayerVersion.split(‘ ‘);
var osType:String = osArray[0]; //The operating system: WIN, MAC, LNX
var versionArray:Array = osArray[1].split(‘,’);//The player versions. 9,0,115,0
var majorVersion:Number = parseInt(versionArray[0]);
var majorRevision:Number = parseInt(versionArray[1]);
var minorVersion:Number = parseInt(versionArray[2]);
var minorRevision:Number = parseInt(versionArray[3]);

vers.text = flashPlayerVersion;
feedback.text = “Operating System: “+osType + “\n” +
“Major Version: “+majorVersion + “\n” +
“Major Revision: “+majorRevision + “\n” +
“Minor Version: “+minorVersion + “\n” +
“Minor Revision: “+minorRevision;

trace(“Operating System: “+osType);
trace(“Major Version: “+majorVersion);
trace(“Major Revision: “+majorRevision);
trace(“Minor Version: “+minorVersion);
trace(“Minor Revision: “+minorRevision);
trace(“–other capabilities–“);
trace(“avHardwareDisable: ” + Capabilities.avHardwareDisable);
trace(“hasAccessibility: ” + Capabilities.hasAccessibility);
trace(“hasAudio: ” + Capabilities.hasAudio);
trace(“hasAudioEncoder: ” + Capabilities.hasAudioEncoder);
trace(“hasEmbeddedVideo: ” + Capabilities.hasEmbeddedVideo);
trace(“hasMP3: ” + Capabilities.hasMP3);
trace(“hasPrinting: ” + Capabilities.hasPrinting);
trace(“hasScreenBroadcast: ” + Capabilities.hasScreenBroadcast);
trace(“hasScreenPlayback: ” + Capabilities.hasScreenPlayback);
trace(“hasStreamingAudio: ” + Capabilities.hasStreamingAudio);
trace(“hasVideoEncoder: ” + Capabilities.hasVideoEncoder);
trace(“isDebugger: ” + Capabilities.isDebugger);
trace(“language: ” + Capabilities.language);
trace(“localFileReadDisable: ” + Capabilities.localFileReadDisable);
trace(“manufacturer: ” + Capabilities.manufacturer);
trace(“os: ” + Capabilities.os);
trace(“pixelAspectRatio: ” + Capabilities.pixelAspectRatio);
trace(“playerType: ” + Capabilities.playerType);
trace(“screenColor: ” + Capabilities.screenColor);
trace(“screenDPI: ” + Capabilities.screenDPI);

trace(“screenResolutionX: ” + Capabilities.screenResolutionX);
trace(“screenResolutionY: ” + Capabilities.screenResolutionY);
trace(“serverString: ” + Capabilities.serverString);
[/cc]

Download

Here’s the source fla file: flash version detection actionscript method (as3)

Copy TextField text to System clipboard | Actionscript (AS2 + AS3) Tutorial

Overview

Integrating the clipboard of the operating system with your flash projects is sometimes essential. It’s a very simple and boils down to one basic method… System.setClipboard(). I’ve found a couple other things help the user experience though, such as selecting the text that gets copied and giving the user some sort of feedback to let them know that the text was successfully copied. Here’s a simple way to do it. Have any suggestions to make it better?

I’ve included an as2 version as well as as3. I’ve promised myself to migrate to as3, so I’m not coding anything in 2 that I don’t do in 3 also. This was to discourage me from coding in as2 and to encourage me to code as3, but also let me learn by doing it in both to see the actual differences if I was stuck doing a project in as2. I figured this could help others see the differences between the two versions of actionscript a bit easier and make their own migration as well!

Steps

  1. copy to OS clipboard = System.setClipboard(“Text to COPY”) of System.setClipboard(textBoxToCopy.text)
  2. set selection to text that is copied
  3. give user feedback

Examples and Source

AS2

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/clipboard_as2.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
textBox.textBox.text = “Click this text box to copy the text or click the COPY button below. You will see feedback to the user and this text copied to your clipboard!\n\n”+
‘copyButton.onRelease = textBox.onPress = function(){\n\tSelection.setFocus(“textBox”);\n\tSelection.setSelection(0, textBox.text.length);\n\tSystem.setClipboard(textBox.text);\n\ttrace(“copied: “+textBox.text);\n\tfeedback(“Text Copied!”);\n}’;

copyButton.onRelease = textBox.onPress = function(){
Selection.setFocus(“textBox.textBox”);
Selection.setSelection(0, textBox.textBox.text.length);
System.setClipboard(textBox.textBox.text);
trace(“copied: “+textBox.textBox.text);
textFeedback(“Text Copied!”);
}

function textFeedback(theFeedback:String){
feedback.text = theFeedback;
setTimeout(function(){feedback.text=””;}, 1200);
}
[/cc]

AS3

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/11/clipboard_as3.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”550″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
textBox.text = “Click this text box to copy the text or click the COPY button below. You will see feedback to the user and this text copied to your clipboard!\n\n”+
‘function copyText(e:MouseEvent):void{\n\ttextBox.setSelection(0, textBox.text.length)\n\tSystem.setClipboard(textBox.text);\n\ttrace(“copied: “+textBox.text);\n\ttextFeedback(“Text Copied!”);\n}’;

//set it so the textBox selection will show even when textBox has no focus
textBox.alwaysShowSelection = true;

textBox.addEventListener(MouseEvent.CLICK, copyText);
copyButton.addEventListener(MouseEvent.CLICK, copyText);

function copyText(e:MouseEvent):void{
textBox.setSelection(0, textBox.text.length)
System.setClipboard(textBox.text);
trace(“copied: “+textBox.text);
textFeedback(“Text Copied!”);
}

function textFeedback(theFeedback:String):void {
feedback.text = theFeedback;
setTimeout(function(){feedback.text=””;}, 1200);
}
[/cc]

Download

Source files: clipboard_as3.fla clipboard_as2+as3.zip