How do I change the background of a Flash document using ActionScript 3.0?

Ed Altorfer picture Ed Altorfer · Oct 17, 2010 · Viewed 10.4k times · Source

Let me preface this question by saying that I am a .NET developer at heart, just helping a friend with a project he is working on.

I have been searching online for something that I think should be pretty simple. Here's what I have:

  1. A standard Flash CS5 document with one layer called background.
  2. The document is associated with a class called 'Game' which extends MovieClip.
  3. I am executing some logic in the 'Game' class after calling an 'Initialize' method.

I want to change the background color of the document at runtime to something else (e.g., a different color, a gradient, or a picture). Simple, right? Maybe not. I can't figure it out. Can some .NET-friendly soul kindly explain how to fix this?

Answer

Jesse picture Jesse · Oct 17, 2010

If you wanted the background to change color, and not have to draw it in, javascript might be a good solution for this problem.

what you change will depend on the embed code, but the param you'll want to change is bgcolor.

in prototype, the javascript would look something like this:

$('yourFlashContainerId').down('[name="bgcolor"]').writeAttribute('value','#000000');

to draw it in flash, you can do something like this:

var bg:Sprite = new Sprite();
bg.graphics.beginFill(0x000000);
bg.graphics.drawRect(0,0,stage.stageWidth, stage.stageHeight);
bg.graphics.endFill();
bg.x = 0;
bg.y = 0;
addChildAt(bg,0);

That will draw a square with a black background (change the hex on line 2 to change the color), set it's size to the size of the stage, set x and y to 0, then add it at the bottom of the display stack.

Either of those two methods should work.

Edit: yet another way:

You could also set the wmode param to "transparent", and change the containing div background color.

assuming your flash embed has the following:

<param name="wmode" value="transparent">

prototype:

$('yourFlashContainerId').setStyle({'background-color':'#000'});

jQuery:

$('#yourFlashContainerId').css({'background-color':'#000'});

native:

document.getElementById('yourFlashContainerId').style.background-color="#000";