flash full browser with swfObject 2

Having had difficulties to find a rather complete description on this very common subject, I thought I might as well compile a selection of techniques necessary to accomplish this.

first, let's go through the requirements within the HTML page and the swfObject javascript, which comes into the head of the HTML page embedding the swf:

HTML:
  1. <script type="text/javascript" src="js/swfobject.js"></script>
  2.     <script type="text/javascript"> 
  3.         //vars and parameters for embedded swf
  4.         var flashvars = { };
  5.         var params = { menu: "false", allowScriptAccess:"sameDomain", allowfullscreen :"true"};
  6.         var attributes = { id: "main", name: "main" };
  7.         swfobject.embedSWF("flash/main.swf", "mainFlash", "100%", "100%", "9.0.0","expressInstall.swf", flashvars, params, attributes); 
  8.     </script>
  9. <style type="text/css">
  10. <!--
  11.   html, body, #mainFlash{ height:100%; width:100%;}
  12.   body { margin:0; padding:0; overflow:hidden; background-color:#A31724; text-align:center; }
  13. -->
  14. </style>

    Set both the width and height of your SWF to 100% in your SWFObject definition.
    Include CSS to get rid of any default margins/padding and set the height of the html element, the body element and the entire chain of block level HTML elements that your SWF will be nested in to 100%, because Firefox (or: any Gecko based browser) in standards compliant mode (or: using a valid DOCTYPE) interprets percentages in a very strict way (to be precise: the percentage of the height of its parent container, which has to be set explicitly)

Now go to your flash movie, and manage the scaling and alignment of your SWF and the positioning of your SWF's elements, within your ActionScript code, e.g.:

Actionscript:
  1. stage.scaleMode = StageScaleMode.NO_SCALE;
  2. stage.align = StageAlign.TOP_LEFT;
  3.  
  4. stage.addEventListener(Event.RESIZE, resizeHandler);
  5.  
  6. function resizeHandler(event:Event):void {
  7.    trace(stage.stageWidth + " x " + stage.stageHeight);
  8.   // center stuff
  9. }

looping video in AS3

Actionscript:
  1. <pre>
  2. package {
  3.  
  4.     import com.onebyonedesign.extras.VideoLoop;
  5.     import flash.display.Sprite;
  6.     import flash.events.AsyncErrorEvent;
  7.     import flash.events.Event;
  8.     import flash.events.MouseEvent;
  9.     import flash.text.AntiAliasType;
  10.     import flash.text.TextField;
  11.     import flash.text.TextFieldAutoSize;
  12.     import flash.text.TextFormat;
  13.     import flash.text.TextFormatAlign;
  14.  
  15.     public class Main extends Sprite {
  16.  
  17.         private var isPlaying:Boolean = true;
  18.         private var videoLoop:VideoLoop;
  19.  
  20.         public function Main():void {
  21.             videoLoop = new VideoLoop("water.flv");
  22.             videoLoop.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
  23.             addChild(videoLoop);
  24.  
  25.             stage.addEventListener(MouseEvent.CLICK, adjustVideo);
  26.  
  27.             var info:TextField = new TextField();
  28.             info.selectable = false;
  29.             info.autoSize = TextFieldAutoSize.LEFT;
  30.             info.antiAliasType = AntiAliasType.ADVANCED;
  31.             var fmt:TextFormat = new TextFormat("_sans", 12, 0x939393);
  32.             fmt.align = TextFormatAlign.CENTER;
  33.             info.defaultTextFormat = fmt;
  34.             info.text = "Two second video looped.\nClick to pause/resume.";
  35.             info.x = 95;
  36.             info.y = 190;
  37.  
  38.             addChild(info);
  39.         }
  40.  
  41.         private function onAsyncError(aee:AsyncErrorEvent):void {
  42.             //  handle annoying async errors (such as the missing metadata property) here.
  43.         }
  44.  
  45.         private function adjustVideo(me:MouseEvent):void {
  46.             if (isPlaying) {
  47.                 videoLoop.pause();
  48.             } else {
  49.                 videoLoop.play();
  50.             }
  51.             isPlaying = !isPlaying;
  52.         }
  53.     }
  54. }</pre>

capture Jpeg live from webcam

For one of my projects that let's the user record a profile video through his webcam, I need to publish a JPEG from the recorded video to later display in an html video list.
After turning the web upside down, I found that byteArrays blog's approach seemed the most suitable one. But he works with AMFPHP, which I did not want to add to the other frameworks already involved with this project, and therefor reconstructed it using a simple PHP solution.
I will continue posting my progress here, and offer src files ASAP.

Another source I found, but haven't evaluated yet, because it is built in AS2, works with PHP's GD image library.

For more information on AMFPHP (aka flash remoting for PHP), which is a remoting service for flash applications, that basically allows flash movies to call remote server side applications. Here is an introduction, but I think that it deserves it's own topic in flashcrobat. I hopefully will soon have time to look deeper into it.

<update >

Ok I have come closer :

http://labs.findsubstance.com/2008/04/03/as3-upload-encode-images/

and :

http://www.hackszine.com/blog/archive/2008/04/encoding_jpegs_clientside_in_a.html

http://henryjones.us/articles/using-the-as3-jpeg-encoder

I am going to try to combine the infos found on several resources, and hope that as an outcome we will have a nice reusable application with which you can make a thumbnail of a clip recorded through your webcam. So let's spit in our hands:

AS3 clipboard functionality

The System.setClipboard() method allows a SWF file to replace the contents of the clipboard with a plain-text string of characters. This poses no security risk. To protect against the risk posed by passwords and other sensitive data being cut or copied to clipboards, there is no corresponding "getClipboard" (read) method.

Flash and JavaScript

I will here collect a series of links of useful information on the interaction between flash and JavaScript, Until I have evaluated all relevant infos, to write a good summary on common practices.

  1. SWFObject has grown up! version 2.0
    • static
    • dynamic
  2. The famous SWFObject to easily embed flash content in html, that was previously hosted on deconcept.com has now moved to google.code basically there are 2 ways to embed your swf into your HTML site:

    more to come...
    her a basic code sample for the integration using swf object, including parameters, flashvars and attributes. (for many external interface interactions, you will need to give your swf an ID and a name)
    here the javascipt to embed:

    
    
    JavaScript:
    1. <script src="http://flashcrobat.noesi.co.uk/js/swfobject.js" type="text/javascript"><!--mce:0--></script>
    2. <script type="text/javascript"><!--mce:1--></script>
    3. <!-- later in the html page comes the div tag where you want your swf to be embedded where you can put in your alternative text, in case someone has javascript disabled, or no flash plugin installed.-->
    4. <div id="swf-div">
    5.     You need Javascript activated and the flash player plugin installed to be able to view this content.
    6. The newest Flash Player can be downloaded here:
    7.  
    8. <a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></div>

    Attention!!:
    giving the id or the name identical name to the swf file causes javascript errors on IE!! took me ages to find the reason for these. So just call your id and name differently than your swf is called.

  3. external interface approach
  4. this seems to be till now the best and easiest reference I found on smooth communicatin between Javascript and the swf in both directions. unfortunatley this only seems to work in AS2. The old fscommand now has been replaced with the externalInterface class. more to read in the Adobe.liveDocs. found on: http://flexion.wordpress.com/ source files: onBoxNet

  5. AS3 Script Injection
  6. Complete and unmodified JavaScript and/or VBScript functions, class objects and applications are stored inside AS3 files using XML, and are then parsed, sent to the browser, and executed. This is an ideal solution for Flash/Flex developers who need JavaScript to interact with the user's browser, but might not have full access to the webpage or server that their SWF application is actually hosted on. Flash Ads, YouTube-style video players, and games that may be hosted across multiple (and possibly unforeseen) webpages are the first things that come to mind. on: actionscript.org

  7. Passing variable from JavaScript To AS3
  8. A brief and basic recollection about passing vars from JS to AS3. found on: metah.ch

  9. Local Connection Actionscript - Communicate between seperate Flash files
  10. Communication between two seperate flash files placed on the same page (or even running simultaneously on one machine) is a nice way to spread a project out. You can send variable, call functions, pretty much do anything in one swf from another. found on: blog.circlecube.com

  11. Flash and Google analytics
  12. This also fits in this cathegory, as most functionalities are handled by Javascript. I will update this entry after have=ing implemented the code on my current Project. found on: flashenabledblog.com

Instance Class or Superclass name: getQualifiedClassName()

sometimes, you want to know the instances class name or the superclass's name. AS3 offers a new function called getQualifiedClassName (flash.utils.getQualifiedClassName) to do just that:

Actionscript:
  1. var sprite:Sprite = new Sprite();
  2. trace(getQualifiedClassName(sprite)); // "flash.display::Sprite"
  3.  
  4. //or to retrieve the name of the super class, use:
  5. trace(getQualifiedSuperclassName(sprite)); // "flash.display::DisplayObjectContainer"

If you actually want to sieve through plenty of info about your instance, try describeType() (flash.utils.describeType).

Actionscript:
  1. var sprite:Sprite = new Sprite();
  2. var spriteDescription:XML = describeType(sprite);
  3. trace (spriteDescription);

try to see....(loads of data coming out here...)

what also fits in here is the use ofgetDefinitionByName()(flash.utils.getDefinitionByName).

avoid new window blocked by Firefox/IE

How annoying! You have your flash application, make a normal external link (a good old www basic), and then the browsers block your external link!, well there seems to be a work around:

Actionscript:
  1. function getURL(url:String,window:String="_blank"):void{
  2.     var broswer:String=ExternalInterface.call("function getBrowser(){return navigator.userAgent}") as String;
  3.     if(broswer.indexOf("Firefox")!=-1 || broswer.indexOf("MSIE 7.0")!=-1){
  4.         ExternalInterface.call('window.open("'+url+'","'+window+'")');
  5.     }else{
  6.         navigateToURL(new URLRequest(url),window);
  7.     }
  8. }

and the most important is set the wmode property is opaque or transparent.

courtesy of:
http://www.riaidea.com/article.asp?id=27(chinese Blog)

Somehow getURL() survived the AS3 code cull, an interesting approach to make it reusable can be found here on Steven Sacks blog. cheers for that one. Would be interesting to combine them to one. TODO:)

passing parameters to Events, custom events

In AS 3.0, if you do want to pass params in your Events you can create your own custom events:

Actionscript:
  1. package{
  2.  
  3. import flash.events.Event;
  4.  
  5. class CustomEvent extends Event{
  6.  
  7. public static const MOUSE_DOWN:String = "onMouseDown";
  8.  
  9. public var myString:String;
  10.  
  11. public function CustomEvent( type:String, str:String ){
  12. myString = str;
  13. super( type );
  14. }//...
  15.  
  16. /*_______you then dispatch this like this______*/
  17.  
  18. //in hboxvar
  19. //you would have to import your custom event
  20. dispatchEvent( new CustomEvent( CustomEvent.MOUSE_DOWN, "1,2,3") )
  21.  
  22. //again you would need to import your custom event
  23. hboxvar.addEventListener( CustomEvent.MOUSE_DOWN, dosomething );
  24.  
  25. private function dosomething( event:CustomEvent ):Void{
  26. trace( event.myString ) // output: 1,2,3
  27. }

another interesting approach can be found here, where flep assigns multiple event types to one custom event, to have more variety in eventHandling.

But probably the most flexible of solutions is to add to the custom Event an Array, as Parameter, alllowing multiple parameters to be passed on when dispatched.

comment: display CustomEvent class 

AS3 textFields

TextFields are created in AS3 basically like most other objects, by first defining and then instantiating them:

Actionscript:
  1. </code>
  2.  
  3. package {
  4. import flash.display.Sprite;
  5. import flash.text.*;
  6. public class whynot extends Sprite{
  7. private var display_txt:TextField;
  8.  
  9. public function whynot(){
  10. display_txt = new TextField();
  11. display_txt.text = "a text";
  12. addChild(display_txt);
  13. }
  14. }
  15. }

Here the code of a function I use for creating my textfields. still basic, but displays the most common settings needed for your dynamic textField. assumingyou have a font added in the library with the class instance name "_tahoma":

Actionscript:
  1. private function makeTextField():void {
  2.  
  3. var tahoma:Font = new _tahoma();
  4.  
  5. TFFormat = new TextFormat();
  6.  
  7. TFFormat.font =tahoma.fontName;
  8. TFFormat.color = "0xFFFFFF";
  9. TFFormat.size = 11;
  10.  
  11. TextField = new TextField();
  12. TextField.width = 200;
  13. TextField.height = height;
  14. TextField.x = 42;
  15. TextField.y = 10;
  16. TextField.wordWrap = true;
  17. TextField.selectable = false;
  18. TextField.border = true;
  19. TextField.multiline = false;
  20. TextField.embedFonts = true;
  21. TextField.autoSize = TextFieldAutoSize.LEFT;
  22. TextField.antiAliasType = AntiAliasType.ADVANCED;
  23.  
  24. addChild(alertTextField);
  25.  
  26. alertTextField.setTextFormat(alertTFFormat);
  27.  
  28. };

One issue I discovered that I can't really explain, is that I often have to reassign the textFormat to the TextField when changing the fields content:

Actionscript:
  1. alertTextField.text = myString;
  2. alertTextField.setTextFormat(alertTFFormat);

setting the focus on an input field:

http://livedocs.adobe.com/flex/201/langref/flash/display/Stage.html#focus

in AS3, it's now a property rather than a function that you call. Also, you don't use the text name value of the field, but a reference to the actual field itself...

would look something like:

Actionscript:
  1. myObj.stage.focus = myTextField;

AS3 MouseEvents and Buttons

first off the link to the class documentation on Adobe Livedocs/MouseEvents:

Actionscript:
  1. //simple way of creating a default Button
  2. package{
  3.    import flash.display.MovieClip;
  4.    import flash.events.MouseEvent;
  5.    public class NavButton extends MovieClip {
  6.       public function NavButton() {
  7.       this.mouseEnabled = true;//to display the hand cursor on Rollover
  8.       this.buttonMode = true;
  9.       this.addEventListener(MouseEvent.ROLL_OVER, dim);
  10.       this.addEventListener(MouseEvent.ROLL_OUT, bright);
  11.       }
  12.       private function  dim ( event:MouseEvent ) : void{
  13.          this.alpha= .75;
  14.       }
  15.       private function bright(event:MouseEvent):void{
  16.          this.alpha = 1;
  17.       }
  18.    }
  19. }


bottom