Flash notes

From Helpful
Jump to: navigation, search
This hasn't been updated for a while, so could be outdated (particularly if it's about something that evolves constantly, such as software).
This article is marked 'feel free.' Often because its authors know they won't spend as much time on it as they should. Your help is appreciated.

This contains large unresearched guesses, and various things may well be specific to Flash 8 or higher without me having realized it yet.


Embedding

If you want cross-browserness and XHTML validity, the best way seems to be:

<object data="movie.swf?any=vars" type="application/x-shockwave-flash" width="500" height="500">
     <param name="movie" value="movie.swf?any=vars"/>
</object>

You can also use something like SWFObject.


Full-window flash:

Will mess with aspect ratio. For any Flash that doesn't specifically deal with that, you may want something like swfresize to make it the largest possible without changing the aspect ratio.

Programming reference

There is some terminology you may want to learn. Doing things primarily or purely from code means a different approach from the point-and-click designing you may be used to.


First of all, some terms: The library (in the flash designer) contains symbols.

A symbol is anything you can re-use - and the concept of things. To see an use them, you instantiate them. Symbols include:

  • Movie Clip: the most general. Also important to scripting.
  • Graphic: anything static, used when you want to do little more than show it. There is little scripting that can apply to these.
  • Button: very minimal, that is, quite sepecific to a purpose
  • ...and also things you can't necessarily or directly see, including Sound objects.


The movie clip is a central concept. Each has its own timeline / layer, which is necessary for them to act independently. Movie clips can contain objects, including other movie clips, so they can easily nest. This means you can make complex and self-contained designs, instantiate them several times, and also do that arbitrarily at runtime.

An MC has its own scope (in the programming sense), has some base functionality and a number of common properties, many of which are graphical. Properties include how and where it is drawn, an optional name, and a way to programmatically navigate through object tree (primarily via _parent</t> and <tt>_root). The root acts as a (slightly special) MovieClip too.

While the flash designer doesn't make it very clear you deal with a tree structure of objects, that is the way it works under the covers when you edit things - you set properties, you go 'into' an MC to edit the instantiation, or a symbol to edit its behaviour.

One of the things that is less immediately mirrored in script and the tree structure includes timeline events and tweening - the interface is quite handy for those.


Interaction is event-based. Movie clips and most everything else can accept events.


Cheat sheets

Documentation


MovieClip, Button, and Textfield share...

Properties

  • _visible (false also implies enabled being false)
  • _alpha
  • _name
  • _x, _y
  • _width, _height
  • _xscale, _yscale, _rotation
  • _parent
  • _target (slashed path to object in object tree. See notes below)
  • _xmouse, _ymouse (local, relative to object origin)
  • _quality (LOW, MEDIUM, HIGH (default), BEST)
  • _url (URL of SWF/image file the MC was based on)
  • tabEnabled, tabIndex
  • menu (context menu, created with Menu tools)

Functions

  • getDepth()

Events

  • onSetFocus, onKillFocus


Notes:

  • Depths are z-index ordering, and need to be specified when creating MCs at runtime (attachMovie(), duplicateMovieClip(), createEmptyMovieClip()). These should be unique - creating with the same depth overwrites the object currently at that depth. Use getNextHighestDepth (which returns the highest occupied depth + 1) to be safe.
  • _target (read-only):
    • To create a dot-notation form of a _target, eval(this._target) it. Can be useful for debug.
    • Can be used to create object reference by assigning to typed object (? (verify))

MovieClip

On top of the shared ones (see above)

Properties

  • _currentframe, _totalframes, _framesloaded
  • _droptarget (target (see notes above) of mc this one was dropped on. maybe set by stopDrag()?)
  • enabled (false disables basic interactivity, and events that aren't basic mouse/key events)
  • focusEnabled (can take input focus?)
  • focusrect (true means 'indicate keyboard focus with yellow border; see also global setting)
  • hitArea (assigns other mc (usually for its shape) for catching mouse events)
  • _lockroot (true ensures the _root of loaded MCs stays refers to its local 'root')
  • trackAsMenu (true prevents other objects from receiving mouse release events)
  • tabChildren (false excludes children from tabbing)
  • useHandCursor
  • _soundbuftime (preload seconds before playing sound. actually a global)


Functions

  • drawing: clear(), beginFill(), beginGradientFill(), endFill(), lineTo(), curveTo(), moveTo(), lineStyle()
  • frame control: nextFrame, prevFrame(), play(), stop(), gotoAndPlay(), gotoAndStop()
  • helpers: localToGlobal(), globalToLocal()
  • status: getBytesLoaded(), getBytesTotal()
  • createEmptyMovieClip(), duplicateMovieClip(), attachMovie(), removeMovieClip()
  • loadMovie(), unloadMovie() SWF, JPEG, PNG, or GIF)
  • createTextField(),
  • startDrag(), stopDrag() (usually called in onPress/onRelease events)
  • getInstanceAtDepth(), getNextHighestDepth()
  • setMask() (use other mc's shape as mask for this one)
  • hitTest()

Events

  • onMouseDown, onMouseUp (triggers when done anywhere)
  • onPress, onRelease, onReleaseOutside (triggers inside MC, except obviously that last one)
  • onMouseMove, onRollOver, onRollOut, onEnterFrame
  • onLoad, onUnload
  • onSetFocus, onKillFocus
  • onDragOver, onDragOut,

TextArea

Button

Others

Mouse

Note: Only has a few global things; most things are done per object.

Functions

  • hide(), show()

Events

  • onMouseDown, onmouseUp, onMouseWheel
  • onMouseMove

System

Properties

  • capabilities (object)
  • security (object)
  • exactSettings
  • useCodepage

Functions

  • setClipboard()
  • showSettings()

Events

  • onStatus

Stage

Properties

  • height, width (read-only)
  • align (T, B, L, R, TL, TR, BL or BR)
  • scaleMode (exactFit, showAll, noBorder, or noScale)
  • showMenu (whwn false, only Settings and About are in the right-click menu)

Events

  • onResize

Sound

Video

XMLSocket

Allows you to communicate with a server with XML both ways - individual messages separated by a single zero byte (as in NUL, 0x00).

You send messages by either using the flash XML class or constructing a string yourself (send() appends the zero byte), and the server response with XML; when Flash receives it, it parses the result and triggers onXML on the XMLSocket object, with the fairly DOM-like root element.

You could choose to close the connection, but it can stay open; it will keep on parsing and triggering, so you could use this for server-based chat, even multi-player games. You do of course need to write a server for this yourself since web servers won't do. (Google for examples, such as [1])

Functions

  • connect(), send(), close()

Events

  • onConnect(), onData(), onXML(), onClose()

LocalConnection

Meant for communication between SWFs on the same page in the browser. Based on named channels. Buggy in some (older) browsers. Flash ≥6.

Properties

  • allowDomain, allowInsecureDomain (should be set to functions)

Functions

  • connect(), send(), close()

Events

  • onStatus

Microphone

You can use the microphone to detect sound levels and play it back (using attachAudio), and this is used with the Flash Communication Server.

Google for examples, such as [2].

Properties (all read-only)

  • activityLevel, silenceLevel, silenceTimeout
  • gain, muted
  • rate
  • name, names, index {{{1}}}
  • useEchoSuppression

Functions

  • get() (default microphone, or by index)
  • setUseEchoSuppression()
  • setGain()
  • setRate()
  • setSilenceLevel() (can also set silenceTimeout)

Events


Actions and events

It seems the flash 5 event model, which looked like:

on(press){
   trace('Our button was pressed');
}

...has been obsoleted by MX 2004 and later, which has a more general and more powerful event system.

From the flash designer, the code in the context of an MC can be something like:

this.onPress = function () {
    this._alpha = 45;
};

If the instantiation is called box, you can also refer to it with that:

box.onRelease = function () {
    this._alpha = 100;
};

In my minimal experience, when you stick to nice event-based coding, the code you can stick in MCs will get you quite far, and your code will mostly be initialisation and attaching event handlers.


You can also add global listener objects:

var interestedObject = new Object()
Key.addListener( interestedObject );
interestedObject.onKeyDown = function(e) {
    trace('you pressed'+Key.getAscii()+' (keycode '+Key.getCode()+')');
}

Programming

Actionscript

ActionScript is based on ECMAscript (and so looks rather like JavaScript), augmented with some handier OO syntax.

  • ActionScript 2 requires Flash 7 or 8,
  • ActionScript 3 requires Flash 9.


Code is associated with keyframes and with objects.

Code is often used to handle events (e.g. button.onRelease), change properties (e.g. mc._x+=10, mc._parent) and command objects or the timeline via functions (e.g. mc.stop(), mc.gotoAndStop())

Pretty much everything you can design you can also generate from code - including shapes. You don't often want to, but you could.


Types

Basics include String, Number, int, uint, null, undefined, Boolean, and other objects.

There are a few things about even these that you may not expect.

  • It seems that Numbers are actually faster than int and uint.
  • It seems that the way the VM does Numbers varies, so you shouldn't e.g. expect them to always have floating-point accuracy(verify)


ActionScript is dynamically typed under the covers, but in 2 and 3 it's considered good style to add types to catch typing errors, like:

var isActive:Boolean = false;
var xs:XMLSocket = new XMLSocket();
var myPoint:flash.geom.Point = new flash.geom.Point(0,0);

Classes, packages

http://livedocs.adobe.com/labs/as3preview/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000030.html

AFLAX

AFLAX (requires flash ≥8) is a javascript-actionscript bridge, apparently created to use standard browser-based AJAX with flash, but useful for many other things. You can control flash from HTML-based javascript, feed it data, get data, create objects, get client data, etc., and all at runtime.


The Aptana IDE has the ability to create a simple AFLAX project for you and has intellisense for it.


These are primarily notes
It won't be complete in any sense.
It exists to contain fragments of useful information.
This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)


AFLAX gives you a page-embedded SWF to interface with (the main object), you can load an SWF into any MC you create later, which you can easily nest.

You can also call functions, get and set members actionscript defined, and add event handlers (which are delegated to JS functions), so you can create JS classes that act more or less transparently like code you would write in AS.

MCs can be told to expose properties (creates a getter and setter) and functions (a shortcut; you can always use callFunction), so that you can code quite like you would in just AS.


Using AFLAX means you don't technically need macromedia's designer, but for most won't be worth the extra work, and I believe there are some slowdowns involved(verify).


I'm not sure yet how it integrates with AS if you want it. Presumably you could add code with MTASC and instantiate those classes, probably meaning you can add in library AS to the AFLAX SWF.

Interacting with properties, functions, events

Exposing properties

Exposing properties via exposeProperty means creating two new functions via introspection. you get a set and a get; the rest of the name is CamelCased - which also means the properties that start with an underscore look different:

_x          -> get_x(), set_x(val)
tabEnabled  -> getTabEnabled(), setTabEnabled(val)

You create these on a specific object, usually the same one, e.g.:

tf = new AFLAX.FlashObject(this.aflax, "TextFormat"); 
tf.exposeProperty("size",tf);
//after which you can use it as:
tf.setSize(14);

Calling functions

When you need it once, you can do it like:

mc.callFunction( 'startDrag', true );

registering event handlers

This registration is basically code that has flash call a javascript function. Since that handler can access flash objects, (and you can easily keep various data on the javascript side) it works well enough.

I believe you do have to do it by string reference, so you'll probably end up doing something like:

var funcs=new Object(); //globally somewhere, perhaps. Depends on how clean you want it
 
funcs['press'+node.id] = function() {
   node.mc.callFunction( 'startDrag', true );
}
 
node.mc.addEventHandler('onPress', 'funcs.press'+node.id+'()');

(In this case, node is a JS object that has a reference to the MovieClip, and the assumption you can have a lot of nodes, each with their unique ID and their unique event)

Flex

Flex is the umbrella term for creating binary SWF from a meta-UI language. From a quick look, it seems open source but not entirely so in spirit (or some details?). It feels limited, perhaps because of the smallish commercial plugins aimed at common business needs, or the non-obvious setup meaning I still don't know what products I need to do what.

I do trust that once I figure it out (given that I care enough to do so) it's pretty neat.


Flex 3:

  • Flex 3 SDK
  • Flex 3 Bulder
  • (not seriously looked at the products yet)


The now older flex 2 (requires Flash player 9) and its various related products:

  • Flex 2 SDK (free), which compiles MXML into SWF, and can use Actionscript and the additional Flex base library.
  • Flex 2 Builder, a paid-for IDE, (~$500)
  • Flex Charting 2, a paid-for product that eases creation of interactive graphs
  • Flex 2 Data Services product, which is a server-side java app
    • primarily useful for middle-end purposes, such as proxying data storage, a general network connection proxy, and some server-client synchronization.
    • can also do on-the-fly-MXML dynamic compilation
    • serious products will reguarly not scale on a the free Express version (one-processor, connection limit, no load balancing); commerical application may require the department ($6,000; few limits), or Enterprise ($20,000, no noticable limits) license.


There are other implementations of similar ideas, such as OpenLaszlo.

Loading things

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits. (Feel free to ignore, fix, or tell me)

HTTP based

  • loadVariables(url,target_mc[,method]):
    • Does HTTP request to the end of setting members in an MC
    • interprets the data it gets as url-encoded form data, e.g. var1="hello"&var2="goodbye"&done="done".
      • Use url-encoded UTF8 for unicode characters(verify). See also [3].
    • target_mc: a direct reference or target path to a MovieClip (or apparently '_self'. Are there more things like this?(verify))
    • non-blocking; if you want to wait for loading, check for one of the variable names and wait for it to stop being undefined
  • Loadvars
    • LoadVars.load(url)
      • Like loadVariables, but works independently of MovieClips.
      • Unlike with loadVariables, there is a loaded property you can check, and an onLoad event (with a boolean parameter, success) that gets triggered when the load is done.
    • LoadVars.send(url,browser_target[,method])
      • Basically a combination of POSTing the variables set on the object and getURL()ing the response.
    • LoadVars.sendAndLoad(url,lv_target[,method])
      • sends the variables present in the object you canned this on, then load()s the response on lv_target(verify).
      • Can be used to synchronize with the server


  • XML.load(url), XML.send, XML.loadAndSend
    • Analogous to LoadVars, but loads into an XML document.


  • MovieClip.loadMovie(url[,method]), MovieClipLoader.loadClip(url[,target])
    • Load a SWF, JPEG, GIF, or PNG into a MovieClip
    • loadMovie into the MC you called this on, loadClip to a specified target.
  • Sound.loadSound(url,isStreaming)
    • Loads an MP3 into the instantiation of Sound you called this on


  • getURL(url[,window[,method]])
    • Instructs browser that is showing the SWF to load another page (verify).
    • window: Name of a window/frame on the browser side, or one of: _self, _blank, _parent, _top. (Default is probably _self(verify))


Other notes:

  • All network loading is restricted to the host that served the SWF. Some do not work in the context of the debugger.
  • An argument called method takes 'GET' or 'POST'.
  • loadVariablesNum, loadMovieNum and such are like the Num-less versions, but send data to a level
  • Apparently in some contexts _self means the SWF, not the browser window(verify)

Page-based

swf URL querystring:

When you stick url-encoded parameters onto the swf URL on the object/embed, those are decoded and stuck onto the _root object.


SWF-to-SWF (on the same page):

Use LocalConnection, see e.g:


Flash-to-javascript, Javascript-to-flash:

There used to be a fscommand('send_var', parameters_string), but this is a bit of a hack, possibly platform-specific, stopped working in recent Flash players.

These recent flash players (8 and 9(verify)) support ExternalInterface instead, which lets Flash access variables and even functions that are in Javascript in the browser document.

It also lets you do the same thing in the other direction, access ActionScript functions, if you register this first.

Notes:

  • I seemed to have some problems in combination with FlashBlock; the way it works may break the connection.

See also:

Upsides and criticism

There is a decent amount of criticism of Flash, and the idea of Flash.

For example, sites that are fully in flash (instead of having a feature or two that is flash) are often disliked somewhat - unless it's eye candy for eye candy's sake, it's just slow and leads itself to various graphical misdesigns, not least of which mystery meat navigation and half-minute loading screens. If you're there for quick, succinct information, snappiness beats all, so you you'ld want a webpage and not Flash.


Usability in Flash usually isn't great. It seems each developer has their own layout ideas, the 'what do you want your buttons to look like' and 'how much harder than in windows 3.1 should that scrollbar be to use' ideas, violating everything in usability theory about user expectation. You can't print, you can't save, and you usually can't bookmark, and most search engines won't index it well.


Full flash means you're not building web pages anymore, it means you're building applications for a specific plugin, basically a variant of Java applets, where Flash is a little easier to install (specifically on linux, though this is often not at all true for the lastest version) and not quite as heavy as Java. Flash has always been software rendered, with the implied limitations, and the ActionScript VM is fast enough for controlling everything up to basic games, but isn't workable for snappy hard calculation on the client side.

Sometimes not building a web page is the point. When you want to deliver web applications, say, a web-served mail client, I would gladly use whatever technology it's in (Flash, Java WS, WPF/E, Silverlight), when its features and speed compare to that of an installed app. The convenience web apps give (e.g. in not having to set up mail configuration each time) is often central to liking a web app over an installed app in the first place.


The fact that there is just one plugin and just one VM can be seen as useful. You don't have all the browser discrepancies that make HTML/CSS/JS webdev such a pain.

The client-side MVC in Flex makes it much easier to build a real GUI in it. However, you don't want things unnecessarily heavyweight.

Legalities

Macromedia's flash player code is under license, meaning the only ways to legally play SWFs is either tha player or an independently developed player.

However, programs can create flash (uncompiled or compiled) as they wish, which allows there to particularly be compilers such as the free and open AS2 compiler by Motion-Twin.


Extensions

Media

See e.g. Browser media and support

Physics

3D


Other

Some reference

Versions

See http://en.wikipedia.org/wiki/Macromedia_Flash

File extensions

  • AS: ActionScript (based on ECMAscript)
  • FLA: editable component files, not directly viewable
  • SWF:
    • compiled, viewable
    • can also be loaded into MCs in other SWFs
    • Can't be edited -- that is, isn't meant to be an editable format, there are decompilers. Also, MTASC can replace the actionscript classes in compiled SWFs.


  • FLV: flash video files, which can be:
    • embedded in the SWF
    • progressively downloaded over http, or
    • streamed from Flash Media Server (RTMP), which allows seeking

Flash itself directly supports loading MP3, PNG, JPG, GIF, and SWF.


Also:

  • AMF: Action Message Format (sometimes ActionScript Message Format), see [4], [5], [6]
  • SOL: Local SharedObject files, see e.g. [7], [8], [9]

See also flashticle, [10]

Links

Still to check:





Somewhat related: