Apr
20
2009

Using filters from Action Script level

To apply filters from Action Script we use "filters" property of every display object. All the available filters are available from flash.filters package. Example below presents how simple is to apply filter to the movie clip instance. Box is a Movie Clip of square placed in library.

First we need to instantiate one of the filters available. I created two variables that are instances of GlowFilter and DropShadowFilter respectively. Filters constructors take plenty of parameters (like color, alpha, strength, etc...), but if we don't pass any, defaults will be used. Flash Help provides list of all parameters and examples. If we want to add or change filter parameters later we can do that by applying new value to a object property like glow.color = 0xFFFFFF. But it's important to remember that when we assign the array of filter instance to the Movie Clip or any other display object, this is actually cloning of this array. So after any change we made to filter instances, we need to overwrite filter property again to take effect.

Removing filter from the display object is the same as removing element from an array. Same as before we need to still overwrite filter property of object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import flash.display.MovieClip;
import flash.filters.*;
 
public class Filters extends MovieClip
{
   var box_mc:Box = new Box();
 
   //default parameters are as follows:
   /*DropShadowFilter(
   distance:Number = 4.0, angle:Number = 45, 
   color:uint = 0, alpha:Number = 1.0, 
   blurX:Number = 4.0, blurY:Number = 4.0, strength:Number = 1.0, 
   quality:int = 1, inner:Boolean = false, 
   knockout:Boolean = false, hideObject:Boolean = false)*/
 
   //Let me set up only the most important parameter for start
   var myShadow:DropShadowFilter = new DropShadowFilter(10, 10, 0xffff00, .5, 2, 2, 1);
 
   //glow filter with defaults
   var myGlow:GlowFilter = new GlowFilter();
 
   var filtersArray:Array = new Array();
 
   public function Filters()
   {
      box_mc.x = box_mc.y = 10;
      addChild(box_mc);
 
      //applying filters table in the following order:
      box_mc.filters = [myShadow, myGlow];
 
      //now it's time to change the shadow color from yellow to red:
      myShadow.color = 0xff0000;
      //reapplying filters table to take effect
      box_mc.filters = [myShadow, myGlow];
 
      //to remove myGlow effect we can use pop() method (as for removing last element from an array)
      //first we need to clone filters table
      filtersArray = box_mc.filters;
      filtersArray.pop();
      //and then reassign it back to the MovieClip
      box_mc.filters = filtersArray;
   }
}
 

AS3 Tips