Building a fullscreen background image with AS3

Today I’ll show you how to build a fullscreen background image using AS3 classes in Adobe Flash. You will learn the meaning of words resize, proportional scale or fullscreen mode. Also you will need a simple image as background.


Preview

Settings all files

Create a new ActionScript File and save it as “MainClass.as” (com.fladev.background.MainClass) – this will be the main class for our flash file; The package classes extends the Sprite class (since we don’t have a timeline animation).
Finnaly create a new AS3 Flash file(550×400px) and open it, so that we have both files opened.


MainClass.as

So we will create a loader that will load the image and then we will resize this image according to stage dimensions.
Let’s add some variables:

private var loader:Loader;
private static const IMAGE_PATH:String = "bg.jpg";//path for external image

The Constructor Function

In constructor function we will add some stage properties like align or scaleMode:

stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, stageResize);

On resize, the hole objects will start to move from top left side (0, 0 coordonates). Also see that listener for stage resize that we didn’t created yet.

We need to load the image from outside before resize, so we need to create a loader.  First create a movieclip symbol on stage with instance name “pic” and set him X and Y to 0,0. Then here in MainClass. in constructor function we create the loader and we attach him as a child to the movieclip created on stage, “pic”.

loader = new Loader();
loader.load(new URLRequest(IMAGE_PATH));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
pic.addChild(loader);

So we load the image through a loader and now we need to show his content.


ShowImage

private function showImage(e:Event):void
		{
			try {
				e.target.content.alpha = 0;
				Tweener.addTween(e.target.content, { alpha:1, time:1, transition:"easeOutSine" } );
				e.target.content.smoothing = true;

			} catch (e:Error) { };
		}

After we load the image trough a loader and the loading process was done, we set this to alpha = 0 and then with Caurina visible to alpha = 1.

The hole function that do the job is stageResize:

private function stageResize(e:Event=null):void
		{
		        //set the movieclip "pic" to 0,0 and scales X and Y to 1;
			pic.x = 0;
			pic.y = 0;
			pic.scaleX = pic.scaleY = 1;

                      //check if the result between stageHeight and stageWidth divided is smaller then the result of pic.height divided with pic.width;
			if ((stage.stageHeight / stage.stageWidth) < pic.height / pic.width) {
				pic.width = stage.stageWidth; //if so the width of "pic" movieclip will take the value of stageWidth;
				pic.scaleY = pic.scaleX;
			} else {
				pic.height = stage.stageHeight;//if not will take the value of stageHeight
				pic.scaleX = pic.scaleY;
			};

                       //pic position (we can set this to 0,0 too)
			pic.x = stage.stageWidth / 2 - pic.width / 2;
			pic.y = stage.stageHeight / 2 - pic.height / 2;

		}

All right, test the movie and see what happenes. Try to resize the window, you can observe the image is resizing as stage. Next step is to create a fullscreen button.


Fullscreen button

In main movie draw a rectangle with background color “#333333“, convert this symbol to be movieclip with instance name fullscreen_btn and make inside 2 frames. On first frame simple write “fullscreen on” and on second frame write “fulscreen off” over the grey background. Create another layer over this, open the actions panel (F9) and put a “stop” action in first frame.


Final step

We need to add a listener for “fulscreen_btn” button, so we can activate the fullscreen function. In constructor add this:

fullscreen_btn.addEventListener(MouseEvent.CLICK, goFullscreen);

Then create a new function goFullscreen:

private function goFullscreen(e:MouseEvent):void
		{
			if( stage.displayState == StageDisplayState.NORMAL ){
				stage.displayState = StageDisplayState.FULL_SCREEN;
			} else {
				stage.displayState = StageDisplayState.NORMAL;
			}
		}

Make a test, see the result so far. The last thing you need to know is that when the display is fullscreen we need a way to know that this happened, or when the display is normal. Add a listener for stage in constructor:

stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreen);

And the function onFullscreen:

private function onFullscreen(e:FullScreenEvent):void
		{
			fullscreen_btn.gotoAndStop(e.fullScreen?2:1);
		}

On fullscreen the button fulscreen_btn will stop to frame 2 “Fulscreen off” and on normal screen will go to frame 1.

Test the movie, see if background have same size as stage and then press the fullscreen button.
When you embed this in html make sure allowFullscreen parameter is true and width or height of .swf is 100%.

That’s it, thank you for your time.


Twitter Digg Delicious Stumbleupon Technorati Facebook

70 Responses to “Building a fullscreen background image with AS3”

  1. Great Script thank you for sharing

    How would I add an Link inside the flash this flash document?

    any suggestions or post threads are greatly appreciated

    thank you!

  2. Great! Thanx!!

  3. How do I get more of a bg to show?

  4. @China: I don’t understand your question, you want to know how to create a button with link inside or what?

    @ricardo: try to make your images to have a properly scale, for example 1024x768px.

  5. hi, great tutorial!! thank you :) but if you want, of course, tell us how to load different random image every time site loads. not slideshow thing, only one random image every time. :)

    thank you in advance
    :)

  6. @dejan: in header you have a single image

    private static const IMAGE_PATH:String = “bg.jpg”;

    Now, you should make an array with few other images, like
    private var images:Array;

    Then in constructor function you will have:
    images = ["img1.jpg, .... img5.jpg];

    Locate where the loader loads the image:
    loader.load(new URLRequest(IMAGE_PATH));

    create here a variable that will give a random number, let’s say:
    var n:Number = Math.floor(1+Math.random()* your_images_length_number);//here you will have a number, from 1 to n.

    then modify the loader line:
    loader.load(new URLRequest(images[n]));

    Recompile and that’s it. Let me know if you have any other questions
    R.

  7. helo robert,

    i have two questions:

    1.i exchanged the image with an .swf and now, the .swf is beeing scaled bigtime. i can’t find the code that does that.

    2. how can i go fully fullscreen by hiding the browser? or should this structur allready do that?

    thanx for the tutorial anyway, good one!

  8. Hi, it’s beeing scaled bigtime becouse must be a fullscreen – see stageResize()

    This have already a listener for fullscreen, search for:

    stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullscreen);

    Cheers!

  9. hi robert,

    that’s what i was guessing.

    but what can i do to resize only the window, but not the content? i was asking anybody and checked a number of tutorials allready…

    e

  10. me again,

    to make it more clearly. i want the page to go fully fullscreen, but i want the content to stay unscaled.

  11. @eric: comment hole content from method “stageResize” and recompile. Cheers

  12. hi robert,

    i did that, but now it just scales a little bit different than before.

    it shouldn’t do that anyway, because of the “stage.scaleMode = StageScaleMode.NO_SCALE;”, right?

    the size of the implemented .swf doesn’t matter, as far as i understand your code.

    rotfcrying

  13. @eric: give me an email with your files, I will do this for you

  14. Hi Robert,
    I get the error “Type was not found: Event” on line private function showImage(e:Event):void ?!
    Thanjks

  15. @Frank: put this after package line:

    import flash.events.Event;

    recompile and will work.

  16. Fantástico trabajo! Perfecto! Es posible añadir más imágenes de fondo que vayan rotando cuando el navegador refresque?
    :-D Gcs Robert

  17. English pls Sarah :)

  18. Is possible using loadvars to load image external?
    thanks

  19. sure, embed the swf with swfaddress and add a parameter there with your image path, then load that parameter and should be ok.

  20. Hi Robert,

    wow, nice offer!

    If you give me your mailadress, i’ll send you the bulk.

    thanx,

    eric

  21. Props Robert!!!
    Excelent Post. (Im an intuitive newbie)

    I would like to have a centered main content.(made in the same .fla).
    Like the content used in xml and flash combined templates.Which I dont like, cause they are hard to modify and not so flexible.

    I want to create my own site with a preloader, change background button,and unsacalable content (movieclip I think?), like erick. This way I can manipulate anyway I want my content having this great fullscreen tweening!!

    I centered my content (movieclip) inside MainClass like this:

    content_mc.x = stage.stageWidth / 2 ;
    content_mc.y = stage.stageHeight / 2 ;

    But I noticed the fullscreen button, and content_mc make a weird jump when they load, I think that they dont start aligned.

    How can we avoid this?
    Can you put a button code for switching backgrounds?

    Thanks, Again for the excellent tut.!!

  22. Hi, It’s excellent to see sites with bing and thanks for the share that you’ve given. Commonly, I’m really amazed, but etc.

  23. Worked Beautifully. Was looking everywhere for how to center images without having that nasty background frame on the sides. Highly useful. Thanks muchly ^^

  24. Nitin pasricha 28. Oct, 2010 at 2:14 pm

    Hi im getting the following error:

    Line 1 1180: Call to a possibly undefined method addFrameScript.

    can someone help me with this. this shows up as soon as i enter stop(); on another keyframe.

  25. You have actions on timeline and the class that extends that object is Sprite instead of MovieClip. Modify to be MovieClip and should be fine.

  26. I am using CS5 as3 and when I compile this i get error: Access of undefined property Tweener and Error: Definition caurina.transitions:Tweener could not be found

    Can anyone help me out please.

    Thanks in advance

  27. You don’t have caurina installed. You have to import that classes in flash ide

  28. Sorry but I can’t see the background from that site. Maybe you can make me some screen shots.

    Cheers

  29. Hi, thanks for the file it is great, I am trying to load an mc onto the stage using the following method:

    var centerBall:ball = new ball();
    centerBall.x = stage.stageWidth / 2;
    centerBall.y = stage.stageHeight / 2;
    addChild(centerBall);

    There are 2 problems, the mc doesn’t appear until I resize the window and also the mc duplicates itself many times as I resize so I end up with many many copies of the mc on the stage.

    I would greatly appreciate your input. Thanks.

  30. the problem is that you put that code inside of the resize function, so anytime you will resize the stage than you will add another instance of that ball. You should add this code outside somewhere, but not in the resize function.

  31. Hi, thanks for the tutorial. I tried to download the source file, but I couldn’t. Am I the only one who couldn’t download or not? Or is there another way to download it? Please let me know. Thanks again :)

  32. Hi Mimi, try again please.

  33. Hi Robert.

    This is Excelent Post that I need.
    But can you make advice how to change background image (or make another post) that use pattern image (Tiled Background) with fullscreen feature so when fullscreen button select, tiled background will grow and cover the area around it depends on the resolution of the monitor used?

  34. Hi Robert,

    Thanks for this amazing tutorial and class.

    I have a question and that is I am loading an swf as the background rather than the bg.jpeg as I would like a preloader to show while the background is loading. However, the swf background does not show until you resize the browser window. Would you have any thoughts as to how the code can be tweaked so that the swf background shows and fills the browser window without having to resize the window first?

  35. @Mark: when the .SWF is fully loaded, for example here loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);

    in showImage function call the stageResize function. Let me know if that works

  36. Hey Robert,

    Thanks for the quick response!!

    Yes, I see that the showimage function is fired and calls the stageResize function when the swf is fully loaded. But the resize does not happen until you resize the window. Nothing shows until the window is resized.

  37. Put your code somewhere and show me

  38. Mark, I replace my image with a simple .SWF and it works. Are you sure you don’t have any Stage actions on that SWF loaded? Unzip again my files and put a simple .SWF here

    private static const IMAGE_PATH:String = “background.swf”;

    and recompile.

  39. There is nothing to do with Sprite or Movieclip. Send me an email with your attachaments, I will take a look.

  40. Nice Tutorial!

    I’ve written a similar tutorial on how to achieve the same effect without using any JavaScript at all. It’s pure css, nice and simple.

    Check it out:
    http://paulmason.name/blog/item/full-screen-background-image-pure-css-code

  41. Nice Tutorial ! Thank you very much

    Could you please tell me how to create a background image sliding with mouse move(left and right move). Like Iphone contact list directory (ex:TwitterTrends in flex Burrito)?

  42. Wonderful Tutorial..

    Dear Robert, Can you please tell, how to add preloader to this tutorial… because when i add any preloader to your tutorial, its not work…

    Thanks…

  43. Dear Robert,

    I’m using this code for preloading but its again getting error..

    ——————–
    loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, preload_image, false, 0, true);

    private function preload_image(event:ProgressEvent):void
    {
    var per = int((event.bytesLoaded / event.bytesTotal) * 100);
    }
    ——————–
    Error is :
    (((((1046: Type was not found or was not a compile-time constant: ProgressEvent.))))

    Can you Help Please…
    Thanks…

  44. Import classes for progress event and will work.

  45. Marvelous Tutorial ! A Truck of Thanks….

    Dear Robert.
    Is it Possible If we can load this pic (MovieClip) on the 2nd frame of FLA??? So I can put my preloader to the 1st frame of my FLA..

  46. Hi Robert,
    I tried to load the class with export classes in 2nd frame and also I tried addframescript but cant do that.. Can you please tell any tip how to load all this to the 2nd frame instead of 1st frame. Is addframescript is the right thing to do this or any thing else, I should try…
    I’ll be very very thankfull to you If you solve this thing..

    Thanks alot…

  47. @Danish – remove from Document Class the Main.as (in Flash). Next step, where the container is link this class – you can find this MovieClip in Library. Move this the to second frame with stop() on both frames. Let me know if this works or not.

    Robert

  48. Hi Robert,
    I’ve tried as you said, But its not working. getting error
    (\com\fladev\background\MainClass.as, Line 38 1120: Access of undefined property pic.)
    A lot of errors of undefined property for pic and fullscreen_btn…
    Sorry I cant help my self to do this..
    If you can Help!… Thanks for Your time..

  49. Hi Robert,
    I’ve already posted the issue..
    Any Tip.. Please Help…

    Thanks…