AS3 stageHeight and stageWidth return 0 at runtime

Posted by
Ziwei

Posted On
Apr 14 2009 1:26 am

Add Comments
Posted in Actionscript, Tutorials

Any experienced flash developer will know that flash contrary to popular belief do not behave the same throughout all browser. From time to time you get frustrating bug that’s never mentioned in any documentation and this bug that grayed a few strand of my hairs is one of them.

If you need to place a movieclip at runtime during initialization of the stage, the movieclip will be added at x:0, y:0 position if you use stageHeight and stageWidth to compute its final position, for instance, the middle of the stage. This is because stageHeight and stageWidth return 0 during the initial loading of the movie before returning the actual stageHeight and stageWidth.

A very straightforward bug but considering that i had only observed it happened in Firefox on OSX and it didn’t trigger every time, it didn’t immediately occurred to me that something is wrong. I thought its just a freak incident until my client observed the same thing.

Fortunately the solution is simple. We simply run a enterframe event listener that constantly check for the value of stageHeight and stageWidth to ensure that its not 0 before we run the rest of the movie. Other alternative include setting a interval timer to ensure that the stage initiated properly before doing anything or simply declare a pair of global variable and hardcode the value of stageHeight and stageWidth into it.

  1. //add eventListener to check for the value of stageHeight and stageWidth
  2. addEventListener(Event.ENTER_FRAME,beginStageDimensionCheck);
  3. function beginStageDimensionCheck(e:Event) {
  4. if (stage.stageWidth>0 && stage.stageHeight>0) {
  5. removeEventListener(Event.ENTER_FRAME,beginStageDimensionCheck); // remove eventListener
  6. runScript(); //execute your script if the value of stageHeight and stageWidth is greater than 0
  7. }
  8. }

Comments ( 0 )

No Comment to “AS3 stageHeight and stageWidth return 0 at runtime” so far

Post Comment

Remember! Spamming is for losers

Trackback from your own website