Packageflash.display
Classpublic class DisplayObject
InheritanceDisplayObject Inheritance EventDispatcher Inheritance Object
Implements IBitmapDrawable
Subclasses AVM1Movie, Bitmap, InteractiveObject, MorphShape, Shape, StaticText, Video

The DisplayObject class is the base class for all objects that can be placed on the display list. The display list manages all objects displayed in Flash Player or Adobe AIR. Use the DisplayObjectContainer class to arrange the display objects in the display list. DisplayObjectContainer objects can have child display objects, while other display objects, such as Shape and TextField objects, are "leaf" nodes that have only parents and siblings, no children.

The DisplayObject class supports basic functionality like the x and y position of an object, as well as more advanced properties of the object such as its transformation matrix.

DisplayObject is an abstract base class; therefore, you cannot call DisplayObject directly. Invoking new DisplayObject() throws an ArgumentError exception.

All display objects inherit from the DisplayObject class.

The DisplayObject class itself does not include any APIs for rendering content onscreen. For that reason, if you want create a custom subclass of the DisplayObject class, you will want to extend one of its subclasses that do have APIs for rendering content onscreen, such as the Shape, Sprite, Bitmap, SimpleButton, TextField, or MovieClip class.

Some properties previously used in the ActionScript 1.0 and 2.0 MovieClip, TextField, and Button classes (such as _alpha, _height, _name, _width, _x, _y, and others) have equivalents in the ActionScript 3.0 DisplayObject class that are renamed so that they no longer begin with the underscore (_) character.

For more information, see the "Display Programming" chapter of the Programming ActionScript 3.0 book.

View the examples

See also

flash.display.DisplayObjectContainer


Public Properties
 PropertyDefined By
  accessibilityProperties : AccessibilityProperties
The current accessibility options for this display object.
DisplayObject
  alpha : Number
Indicates the alpha transparency value of the object specified.
DisplayObject
  blendMode : String
A value from the BlendMode class that specifies which blend mode to use.
DisplayObject
  cacheAsBitmap : Boolean
If set to true, Flash Player or Adobe AIR caches an internal bitmap representation of the display object.
DisplayObject
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  filters : Array
An indexed array that contains each filter object currently associated with the display object.
DisplayObject
  height : Number
Indicates the height of the display object, in pixels.
DisplayObject
  loaderInfo : LoaderInfo
[read-only] Returns a LoaderInfo object containing information about loading the file to which this display object belongs.
DisplayObject
  mask : DisplayObject
The calling display object is masked by the specified mask object.
DisplayObject
  mouseX : Number
[read-only] Indicates the x coordinate of the mouse position, in pixels.
DisplayObject
  mouseY : Number
[read-only] Indicates the y coordinate of the mouse position, in pixels.
DisplayObject
  name : String
Indicates the instance name of the DisplayObject.
DisplayObject
  opaqueBackground : Object
Specifies whether the display object is opaque with a certain background color.
DisplayObject
  parent : DisplayObjectContainer
[read-only] Indicates the DisplayObjectContainer object that contains this display object.
DisplayObject
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  root : DisplayObject
[read-only] For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file.
DisplayObject
  rotation : Number
Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation.
DisplayObject
  scale9Grid : Rectangle
The current scaling grid that is in effect.
DisplayObject
  scaleX : Number
Indicates the horizontal scale (percentage) of the object as applied from the registration point.
DisplayObject
  scaleY : Number
Indicates the vertical scale (percentage) of an object as applied from the registration point of the object.
DisplayObject
  scrollRect : Rectangle
The scroll rectangle bounds of the display object.
DisplayObject
  stage : Stage
[read-only] The Stage of the display object.
DisplayObject
  transform : Transform
An object with properties pertaining to a display object's matrix, color transform, and pixel bounds.
DisplayObject
  visible : Boolean
Whether or not the display object is visible.
DisplayObject
  width : Number
Indicates the width of the display object, in pixels.
DisplayObject
  x : Number
Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.
DisplayObject
  y : Number
Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer.
DisplayObject
Public Methods
 MethodDefined By
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
 Inherited
Dispatches an event into the event flow.
EventDispatcher
  
getBounds(targetCoordinateSpace:DisplayObject):Rectangle
Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object.
DisplayObject
  
getRect(targetCoordinateSpace:DisplayObject):Rectangle
Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes.
DisplayObject
  
Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates.
DisplayObject
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
  
Evaluates the display object to see if it overlaps or intersects with the obj display object.
DisplayObject
  
hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean
Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters.
DisplayObject
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.
DisplayObject
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 Event Summary Defined By
 Inherited Dispatched when Flash Player or an AIR application gains operating system focus and becomes active.EventDispatcher
   Dispatched when a display object is added to the display list.DisplayObject
   Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained.DisplayObject
 Inherited Dispatched when Flash Player or an AIR application loses operating system focus and is becoming inactive.EventDispatcher
   Dispatched when the playhead is entering a new frame.DisplayObject
   Dispatched when a display object is about to be removed from the display list.DisplayObject
   Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained.DisplayObject
   Dispatched when the display list is about to be updated and rendered.DisplayObject
Property Detail
accessibilityPropertiesproperty
accessibilityProperties:AccessibilityProperties  [read-write]

The current accessibility options for this display object. If you modify the accessibilityProperties property or any of the fields within accessibilityProperties, you must call the Accessibility.updateProperties() method to make your changes take effect.


Implementation
    public function get accessibilityProperties():AccessibilityProperties
    public function set accessibilityProperties(value:AccessibilityProperties):void

See also


Example

The following example shows how the to attach a simple AccessibilityProperties object to a TextField instance:

import flash.text.TextField;
import flash.accessibility.AccessibilityProperties;
import flash.accessibility.Accessibility;
import flash.system.Capabilities;

var tf:TextField = new TextField();
tf.text = "hello";

var accessProps:AccessibilityProperties = new AccessibilityProperties();
accessProps.name = "Greeting";

tf.accessibilityProperties = accessProps;

if (Capabilities.hasAccessibility) {
    Accessibility.updateProperties();
}

trace(tf.accessibilityProperties.name); // Greeting
alphaproperty 
alpha:Number  [read-write]

Indicates the alpha transparency value of the object specified. Valid values are 0 (fully transparent) to 1 (fully opaque). The default value is 1. Display objects with alpha set to 0 are active, even though they are invisible.


Implementation
    public function get alpha():Number
    public function set alpha(value:Number):void

Example

The following code sets the alpha property of a sprite to 50% when the mouse rolls over the sprite:
import flash.display.Sprite;
import flash.events.MouseEvent;

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFF0000);
circle.graphics.drawCircle(40, 40, 40);
addChild(circle);

circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject);
circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject);

function dimObject(event:MouseEvent):void {
    event.target.alpha = 0.5;
}

function restoreObject(event:MouseEvent):void {
    event.target.alpha = 1.0;
}
blendModeproperty 
blendMode:String  [read-write]

A value from the BlendMode class that specifies which blend mode to use. A bitmap can be drawn internally in two ways. If you have a blend mode enabled or an external clipping mask, the bitmap is drawn by adding a bitmap-filled square shape to the vector render. If you attempt to set this property to an invalid value, Flash Player or Adobe AIR sets the value to BlendMode.NORMAL.

The blendMode property affects each pixel of the display object. Each pixel is composed of three constituent colors (red, green, and blue), and each constituent color has a value between 0x00 and 0xFF. Flash Player or Adobe AIR compares each constituent color of one pixel in the movie clip with the corresponding color of the pixel in the background. For example, if blendMode is set to BlendMode.LIGHTEN, Flash Player or Adobe AIR compares the red value of the display object with the red value of the background, and uses the lighter of the two as the value for the red component of the displayed color.

The following table describes the blendMode settings. The BlendMode class defines string values you can use. The illustrations in the table show blendMode values applied to a circular display object (2) superimposed on another display object (1).

BlendMode ConstantIllustrationDescription
BlendMode.NORMALThe display object appears in front of the background. Pixel values of the display object override those of the background. Where the display object is transparent, the background is visible.
BlendMode.LAYERForces the creation of a transparency group for the display object. This means that the display object is pre-composed in a temporary buffer before it is processed further. This is done automatically if the display object is pre-cached using bitmap caching or if the display object is a display object container with at least one child object with a blendMode setting other than BlendMode.NORMAL.
BlendMode.MULTIPLYMultiplies the values of the display object constituent colors by the colors of the background color, and then normalizes by dividing by 0xFF, resulting in darker colors. This setting is commonly used for shadows and depth effects.

For example, if a constituent color (such as red) of one pixel in the display object and the corresponding color of the pixel in the background both have the value 0x88, the multiplied result is 0x4840. Dividing by 0xFF yields a value of 0x48 for that constituent color, which is a darker shade than the color of the display object or the color of the background.

BlendMode.SCREENMultiplies the complement (inverse) of the display object color by the complement of the background color, resulting in a bleaching effect. This setting is commonly used for highlights or to remove black areas of the display object.
BlendMode.LIGHTENSelects the lighter of the constituent colors of the display object and the color of the background (the colors with the larger values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xFFF833 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

BlendMode.DARKENSelects the darker of the constituent colors of the display object and the colors of the background (the colors with the smaller values). This setting is commonly used for superimposing type.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0xDDCC00 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

BlendMode.DIFFERENCECompares the constituent colors of the display object with the colors of its background, and subtracts the darker of the values of the two constituent colors from the lighter value. This setting is commonly used for more vibrant colors.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0x222C33 (because 0xFF - 0xDD = 0x22, 0xF8 - 0xCC = 0x2C, and 0x33 - 0x00 = 0x33).

BlendMode.ADDAdds the values of the constituent colors of the display object to the colors of its background, applying a ceiling of 0xFF. This setting is commonly used for animating a lightening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAAA633, and the background pixel has an RGB value of 0xDD2200, the resulting RGB value for the displayed pixel is 0xFFC833 (because 0xAA + 0xDD > 0xFF, 0xA6 + 0x22 = 0xC8, and 0x33 + 0x00 = 0x33).

BlendMode.SUBTRACTSubtracts the values of the constituent colors in the display object from the values of the background color, applying a floor of 0. This setting is commonly used for animating a darkening dissolve between two objects.

For example, if the display object has a pixel with an RGB value of 0xAA2233, and the background pixel has an RGB value of 0xDDA600, the resulting RGB value for the displayed pixel is 0x338400 (because 0xDD - 0xAA = 0x33, 0xA6 - 0x22 = 0x84, and 0x00 - 0x33 < 0x00).

BlendMode.INVERTInverts the background.
BlendMode.ALPHAApplies the alpha value of each pixel of the display object to the background. This requires the blendMode setting of the parent display object to be set to BlendMode.LAYER. For example, in the illustration, the parent display object, which is a white background, has blendMode = BlendMode.LAYER.
BlendMode.ERASEErases the background based on the alpha value of the display object. This requires the blendMode of the parent display object to be set to BlendMode.LAYER. For example, in the illustration, the parent display object, which is a white background, has blendMode = BlendMode.LAYER.
BlendMode.OVERLAYAdjusts the color of each pixel based on the darkness of the background. If the background is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the background is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects.
BlendMode.HARDLIGHTAdjusts the color of each pixel based on the darkness of the display object. If the display object is lighter than 50% gray, the display object and background colors are screened, which results in a lighter color. If the display object is darker than 50% gray, the colors are multiplied, which results in a darker color. This setting is commonly used for shading effects.


Implementation
    public function get blendMode():String
    public function set blendMode(value:String):void

See also


Example

The following code creates two sprite objects, a square and a circle, and sets the blend mode of the circle (in the foreground) to BlendMode.SUBTRACT when the pointer rolls over the circle:
import flash.display.Sprite;
import flash.display.BlendMode;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF88CC);
square.graphics.drawRect(0, 0, 80, 80);
addChild(square);

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xAA0022);
circle.graphics.drawCircle(40, 40, 40);
addChild(circle);

circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject);
circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject);

function dimObject(event:MouseEvent):void {
    event.target.blendMode = BlendMode.SUBTRACT;
}

function restoreObject(event:MouseEvent):void {
    event.target.blendMode = BlendMode.NORMAL;
}
cacheAsBitmapproperty 
cacheAsBitmap:Boolean  [read-write]

If set to true, Flash Player or Adobe AIR caches an internal bitmap representation of the display object. This caching can increase performance for display objects that contain complex vector content.

All vector data for a display object that has a cached bitmap is drawn to the bitmap instead of the main display. The bitmap is then copied to the main display as unstretched, unrotated pixels snapped to the nearest pixel boundaries. Pixels are mapped 1 to 1 with the parent object. If the bounds of the bitmap change, the bitmap is recreated instead of being stretched.

No internal bitmap is created unless the cacheAsBitmap property is set to true.

After you set the cacheAsBitmap property to true, the rendering does not change, however the display object performs pixel snapping automatically. The animation speed can be significantly faster depending on the complexity of the vector content.

The cacheAsBitmap property is automatically set to true whenever you apply a filter to a display object (when its filter array is not empty), and if a display object has a filter applied to it, cacheAsBitmap is reported as true for that display object, even if you set the property to false. If you clear all filters for a display object, the cacheAsBitmap setting changes to what it was last set to.

A display object does not use a bitmap even if the cacheAsBitmap property is set to true and instead renders from vector data in the following cases:

The cacheAsBitmap property is best used with movie clips that have mostly static content and that do not scale and rotate frequently. With such movie clips, cacheAsBitmap can lead to performance increases when the movie clip is translated (when its x and y position is changed).


Implementation
    public function get cacheAsBitmap():Boolean
    public function set cacheAsBitmap(value:Boolean):void

See also


Example

The following example applies a drop shadow to a Shape instance. It then traces the value of the cacheAsBitmap property, which is set to true when the filter is applied:
import flash.display.Sprite;
import flash.filters.DropShadowFilter

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xAA0022);
circle.graphics.drawCircle(40, 40, 40);

addChild(circle);

trace(circle.cacheAsBitmap); // false

var filter:DropShadowFilter = new DropShadowFilter();
circle.filters = [filter];

trace(circle.cacheAsBitmap); // true
filtersproperty 
filters:Array  [read-write]

An indexed array that contains each filter object currently associated with the display object. The flash.filters package contains several classes that define specific filters you can use.

Filters can be applied in the Flash authoring tool at design-time, or at runtime by using ActionScript code. To apply a filter by using ActionScript, you must make a temporary copy of the entire filters array, modify the temporary array, then assign the value of the temporary array back to the filters array. You cannot directly add a new filter object to the filters array.

To add a filter by using ActionScript, perform the following steps (assume that the target display object is named myDisplayObject):

  1. Create a new filter object by using the constructor method of your chosen filter class.
  2. Assign the value of the myDisplayObject.filters array to a temporary array, such as one named myFilters.
  3. Add the new filter object to the myFilters temporary array.
  4. Assign the value of the temporary array to the myDisplayObject.filters array.

If the filters array is undefined, you do not need to use a temporary array. Instead, you can directly assign an array literal that contains one or more filter objects that you create. The first example in the Examples section adds a drop shadow filter by using code that handles both defined and undefined filters arrays.

To modify an existing filter object, you must use the technique of modifying a copy of the filters array:

  1. Assign the value of the filters array to a temporary array, such as one named myFilters.
  2. Modify the property by using the temporary array, myFilters. For example, to set the quality property of the first filter in the array, you could use the following code: myFilters[0].quality = 1;
  3. Assign the value of the temporary array to the filters array.

At load time, if a display object has an associated filter, it is marked to cache itself as a transparent bitmap. From this point forward, as long as the display object has a valid filter list, the player caches the display object as a bitmap. This source bitmap is used as a source image for the filter effects. Each display object usually has two bitmaps: one with the original unfiltered source display object and another for the final image after filtering. The final image is used when rendering. As long as the display object does not change, the final image does not need updating.

The flash.filters package includes classes for filters. For example, to create a DropShadow filter, you would write:

     import flash.filters.DropShadowFilter
     var myFilter:DropShadowFilter = new DropShadowFilter (distance, angle, color, alpha, blurX, blurY, quality, inner, knockout)
     

You can use the is operator to determine the type of filter assigned to each index position in the filter array. For example, the following code shows how to determine the position of the first filter in the filters array that is a DropShadowFilter:

     import flash.text.TextField;
     import flash.filters.*;
     var tf:TextField = new TextField();
     var filter1:DropShadowFilter = new DropShadowFilter();
     var filter2:GradientGlowFilter = new GradientGlowFilter();
     tf.filters = [filter1, filter2];
     
     tf.text = "DropShadow index: " + filterPosition(tf, DropShadowFilter).toString(); // 0
     addChild(tf)
     
     function filterPosition(displayObject:DisplayObject, filterClass:Class):int {
         for (var i:uint = 0; i < displayObject.filters.length; i++) {
             if (displayObject.filters[i] is filterClass) {
                 return i;
             }
         }
         return -1;
     }
     

Note: Since you cannot directly add a new filter object to the DisplayObject.filters array, the following code has no effect on the target display object, named myDisplayObject:

     myDisplayObject.filters.push(myDropShadow);
     


Implementation
    public function get filters():Array
    public function set filters(value:Array):void

See also

heightproperty 
height:Number  [read-write]

Indicates the height of the display object, in pixels. The height is calculated based on the bounds of the content of the display object. When you set the height property, the scaleY property is adjusted accordingly, as shown in the following code:

 var rect:Shape = new Shape();
 rect.graphics.beginFill(0xFF0000);
 rect.graphics.drawRect(0, 0, 100, 100);
 trace(rect.scaleY) // 1;
 rect.height = 200;
 trace(rect.scaleY) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a height of 0, even if you try to set height to a different value.


Implementation
    public function get height():Number
    public function set height(value:Number):void

Example

The following code creates two TextField objects and adjusts the height property of each based on the textHeight property of each; it also positions the second text field by setting its y property:
import flash.text.TextField;

var tf1:TextField = new TextField();
tf1.text = "Text Field 1";
tf1.border = true;
tf1.wordWrap = true;
tf1.width = 40;
tf1.height = tf1.textHeight + 5;
addChild(tf1);

var tf2:TextField = new TextField();
tf2.text = "Text Field 2";
tf2.border = true;
tf2.wordWrap = true;
tf2.width = 40;
tf2.height = tf2.textHeight + 5;
tf2.y = tf1.y + tf1.height + 5;
addChild(tf2);
loaderInfoproperty 
loaderInfo:LoaderInfo  [read-only]

Returns a LoaderInfo object containing information about loading the file to which this display object belongs. The loaderInfo property is defined only for the root display object of a SWF file or for a loaded Bitmap (not for a Bitmap that is drawn with ActionScript). To find the loaderInfo object associated with the SWF file that contains a display object named myDisplayObject, use myDisplayObject.root.loaderInfo.

A large SWF file can monitor its download by calling this.root.loaderInfo.addEventListener(Event.COMPLETE, func).


Implementation
    public function get loaderInfo():LoaderInfo

See also


Example

The following code assumes that this refers to a display object. The code outputs the URL of the root SWF file for the display object:
trace(this.loaderInfo.url);
 
maskproperty 
mask:DisplayObject  [read-write]

The calling display object is masked by the specified mask object. To ensure that masking works when the Stage is scaled, the mask display object must be in an active part of the display list. The mask object itself is not drawn. Set mask to null to remove the mask.

To be able to scale a mask object, it must be on the display list. To be able to drag a mask Sprite object (by calling its startDrag() method), it must be on the display list. To call the startDrag() method for a mask sprite based on a mouseDown event being dispatched by the sprite, set the sprite's buttonMode property to true.


Implementation
    public function get mask():DisplayObject
    public function set mask(value:DisplayObject):void

Example

The following code creates a TextField object as well as a Sprite object that is set as a mask for the TextField object. When the user clicks the text field, the drag() event listener function calls the startDrag() method of the mask Sprite object:
import flash.text.TextField;
import flash.display.Sprite;
import flash.events.MouseEvent;

var tf:TextField = new TextField();
tf.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " 
            + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
tf.selectable = false;
tf.wordWrap = true;
tf.width = 150;
addChild(tf);

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0, 0, 40, 40);
addChild(square);

tf.mask = square;

tf.addEventListener(MouseEvent.MOUSE_DOWN, drag);
tf.addEventListener(MouseEvent.MOUSE_UP, noDrag);

function drag(event:MouseEvent):void {
    square.startDrag();
}
function noDrag(event:MouseEvent):void {
    square.stopDrag();
}
mouseXproperty 
mouseX:Number  [read-only]

Indicates the x coordinate of the mouse position, in pixels.


Implementation
    public function get mouseX():Number

Example

The following code creates a Sprite object and traces the mouseX and mouseY positions when the user clicks the sprite:
import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0, 0, 200, 200);
addChild(square);

square.addEventListener(MouseEvent.CLICK, traceCoordinates);

function traceCoordinates(event:MouseEvent):void {
    trace(square.mouseX, square.mouseY);
}
mouseYproperty 
mouseY:Number  [read-only]

Indicates the y coordinate of the mouse position, in pixels.


Implementation
    public function get mouseY():Number

Example

The following code creates a Sprite object and traces the mouseX and mouseY positions when the user clicks the sprite:
import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0, 0, 200, 200);
addChild(square);

square.addEventListener(MouseEvent.CLICK, traceCoordinates);

function traceCoordinates(event:MouseEvent):void {
    trace(square.mouseX, square.mouseY);
}
nameproperty 
name:String  [read-write]

Indicates the instance name of the DisplayObject. The object can be identified in the child list of its parent display object container by calling the getChildByName() method of the display object container.


Implementation
    public function get name():String
    public function set name(value:String):void

Throws
IllegalOperationError — If you are attempting to set this property on an object that was placed on the timeline in the Flash authoring tool.

Example

The following code creates two Sprite object and traces the associated name property when the user clicks either of the objects:
import flash.display.Sprite;
import flash.events.MouseEvent;

var circle1:Sprite = new Sprite();
circle1.graphics.beginFill(0xFF0000);
circle1.graphics.drawCircle(40, 40, 40);
circle1.name = "circle1";
addChild(circle1);
circle1.addEventListener(MouseEvent.CLICK, traceName);

var circle2:Sprite = new Sprite();
circle2.graphics.beginFill(0x0000FF);
circle2.graphics.drawCircle(140, 40, 40);
circle2.name = "circle2";
addChild(circle2);
circle2.addEventListener(MouseEvent.CLICK, traceName);

function traceName(event:MouseEvent):void {
    trace(event.target.name);
}
opaqueBackgroundproperty 
opaqueBackground:Object  [read-write]

Specifies whether the display object is opaque with a certain background color. A transparent bitmap contains alpha channel data and is drawn transparently. An opaque bitmap has no alpha channel (and renders faster than a transparent bitmap). If the bitmap is opaque, you specify its own background color to use.

If set to a number value, the surface is opaque (not transparent) with the RGB background color that the number specifies. If set to null (the default value), the display object has a transparent background.

The opaqueBackground property is intended mainly for use with the cacheAsBitmap property, for rendering optimization. For display objects in which the cacheAsBitmap property is set to true, setting opaqueBackground can improve rendering performance.

The opaque background region is not matched when calling the hitTestPoint() method with the shapeFlag parameter set to true.

The opaque background region does not respond to mouse events.


Implementation
    public function get opaqueBackground():Object
    public function set opaqueBackground(value:Object):void

See also


Example

The following code creates a Shape object with a blue circle and sets its opaqueBackground property to red (0xFF0000):
import flash.display.Shape;

var circle:Shape = new Shape();
circle.graphics.beginFill(0x0000FF);
circle.graphics.drawCircle(40, 40, 40);
circle.opaqueBackground = 0xFF0000;
addChild(circle);
parentproperty 
parent:DisplayObjectContainer  [read-only]

Indicates the DisplayObjectContainer object that contains this display object. Use the parent property to specify a relative path to display objects that are above the current display object in the display list hierarchy.

You can use parent to move up multiple levels in the display list as in the following:

     this.parent.parent.alpha = 20;
     


Implementation
    public function get parent():DisplayObjectContainer

Throws
SecurityError — The parent display object belongs to a security sandbox to which you do not have access. You can avoid this situation by having the parent movie call the Security.allowDomain() method.

Example

The following code creates three Sprite objects and shows how the parent property reflects the display list hierarchy:

import flash.display.Sprite;

var sprite1:Sprite = new Sprite();
sprite1.name = "sprite1";
var sprite2:Sprite = new Sprite();
sprite2.name = "sprite2";
var sprite3:Sprite = new Sprite();
sprite3.name = "sprite3";

sprite1.addChild(sprite2);
sprite2.addChild(sprite3);

trace(sprite2.parent.name); // sprite1
trace(sprite3.parent.name); // sprite2
trace(sprite3.parent.parent.name); // sprite1
rootproperty 
root:DisplayObject  [read-only]

For a display object in a loaded SWF file, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file. For a Bitmap object representing a loaded image file, the root property is the Bitmap object itself. For the instance of the main class of the first SWF file loaded, the root property is the display object itself. The root property of the Stage object is the Stage object itself. The root property is set to null for any display object that has not been added to the display list, unless it has been added to a display object container that is off the display list but that is a child of the top-most display object in a loaded SWF file.

For example, if you create a new Sprite object by calling the Sprite() constructor method, its root property is null until you add it to the display list (or to a display object container that is off the display list but that is a child of the top-most display object in a SWF file).

For a loaded SWF file, even though the Loader object used to load the file may not be on the display list, the top-most display object in the SWF file has its root property set to itself. The Loader object does not have its root property set until it is added as a child of a display object for which the root property is set.


Implementation
    public function get root():DisplayObject

Example

The following code shows the difference between the root property for the Stage object, for a display object (a Loader object) that is not loaded (both before and after it has been added to the display list), and for a loaded object (a loaded Bitmap object):
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;

trace(stage.root); // [object Stage]

var ldr:Loader = new Loader();
trace(ldr.root); // null

addChild(ldr); 
trace(ldr.root); // [object ...]

var urlReq:URLRequest = new URLRequest("example.jpg");
ldr.load(urlReq);

ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);

function loaded(event:Event):void {
    trace(ldr.content.root); // [object Bitmap]
}
rotationproperty 
rotation:Number  [read-write]

Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement my_video.rotation = 450 is the same as my_video.rotation = 90.


Implementation
    public function get rotation():Number
    public function set rotation(value:Number):void

Example

The following code creates a Sprite object and rotates the object when the user clicks it:

import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFCC00);
square.graphics.drawRect(-50, -50, 100, 100);
square.x = 150;
square.y = 150;
addChild(square);

square.addEventListener(MouseEvent.CLICK, rotate);

function rotate(event:MouseEvent):void {
        square.rotation += 15;
}
scale9Gridproperty 
scale9Grid:Rectangle  [read-write]

The current scaling grid that is in effect. If set to null, the entire display object is scaled normally when any scale transformation is applied.

When you define the scale9Grid property, the display object is divided into a grid with nine regions based on the scale9Grid rectangle, which defines the center region of the grid. The eight other regions of the grid are the following areas:

You can think of the eight regions outside of the center (defined by the rectangle) as being like a picture frame that has special rules applied to it when scaled.

When the scale9Grid property is set and a display object is scaled, all text and gradients are scaled normally; however, for other types of objects the following rules apply:

If a display object is rotated, all subsequent scaling is normal (and the scale9Grid property is ignored).

For example, consider the following display object and a rectangle that is applied as the display object's scale9Grid:

The display object.

The red rectangle shows the scale9Grid.

When the display object is scaled or stretched, the objects within the rectangle scale normally, but the objects outside of the rectangle scale according to the scale9Grid rules:

Scaled to 75%:
Scaled to 50%:
Scaled to 25%:
Stretched horizontally 150%:

A common use for setting scale9Grid is to set up a display object to be used as a component, in which edge regions retain the same width when the component is scaled.


Implementation
    public function get scale9Grid():Rectangle
    public function set scale9Grid(value:Rectangle):void

Throws
ArgumentError — If you pass an invalid argument to the method.

See also


Example

The following code creates a Shape object with a rectangle drawn in its graphics property. The rectangle has a 20-pixel-thick line as the border and it is filled with a gradient. The timer event calls the scale() function, which scales the Shape object by adjusting the scaleX and scaleY properties. The scale9Grid applied to the Shape object prevents the rectangle's border line from scaling — only the gradient fill scales:

import flash.display.Shape;
import flash.display.GradientType;
import flash.display.SpreadMethod;
import flash.display.InterpolationMethod;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.utils.Timer;
import flash.events.TimerEvent;

var square:Shape = new Shape();
square.graphics.lineStyle(20, 0xFFCC00);
var gradientMatrix:Matrix = new Matrix();
gradientMatrix.createGradientBox(15, 15, Math.PI, 10, 10);
square.graphics.beginGradientFill(GradientType.RADIAL, 
            [0xffff00, 0x0000ff], 
            [100, 100], 
            [0, 0xFF], 
            gradientMatrix, 
            SpreadMethod.REFLECT, 
            InterpolationMethod.RGB, 
            0.9);
square.graphics.drawRect(0, 0, 100, 100);

var grid:Rectangle = new Rectangle(20, 20, 60, 60);
square.scale9Grid = grid ;

addChild(square);

var tim:Timer = new Timer(100);
tim.start();
tim.addEventListener(TimerEvent.TIMER, scale);

var scaleFactor:Number = 1.01;

function scale(event:TimerEvent):void {
    square.scaleX *= scaleFactor;
    square.scaleY *= scaleFactor;
    
    if (square.scaleX > 2.0) {
        scaleFactor = 0.99;
    }
    if (square.scaleX < 1.0) {
        scaleFactor = 1.01;
    }
}
scaleXproperty 
scaleX:Number  [read-write]

Indicates the horizontal scale (percentage) of the object as applied from the registration point. The default registration point is (0,0). 1.0 equals 100% scale.

Scaling the local coordinate system affects the x and y property settings, which are defined in whole pixels.


Implementation
    public function get scaleX():Number
    public function set scaleX(value:Number):void

Example

The following code creates a Sprite object with a rectangle drawn in its graphics property. When the user clicks the sprite, it scales by 10%:

import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFCC00);
square.graphics.drawRect(0, 0, 100, 100);
addChild(square);

square.addEventListener(MouseEvent.CLICK, scale);

function scale(event:MouseEvent):void {
    square.scaleX *= 1.10;
    square.scaleY *= 1.10;
}
scaleYproperty 
scaleY:Number  [read-write]

Indicates the vertical scale (percentage) of an object as applied from the registration point of the object. The default registration point is (0,0). 1.0 is 100% scale.

Scaling the local coordinate system affects the x and y property settings, which are defined in whole pixels.


Implementation
    public function get scaleY():Number
    public function set scaleY(value:Number):void

Example

The following code creates a Sprite object with a rectangle drawn in its graphics property. When the user clicks the sprite, it scales by 10%:

import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFCC00);
square.graphics.drawRect(0, 0, 100, 100);
addChild(square);

square.addEventListener(MouseEvent.CLICK, scale);

function scale(event:MouseEvent):void {
    square.scaleX *= 1.10;
    square.scaleY *= 1.10;
}
scrollRectproperty 
scrollRect:Rectangle  [read-write]

The scroll rectangle bounds of the display object. The display object is cropped to the size defined by the rectangle, and it scrolls within the rectangle when you change the x and y properties of the scrollRect object.

The properties of the scrollRect Rectangle object use the display object's coordinate space and are scaled just like the overall display object. The corner bounds of the cropped window on the scrolling display object are the origin of the display object (0,0) and the point defined by the width and height of the rectangle. They are not centered around the origin, but use the origin to define the upper-left corner of the area. A scrolled display object always scrolls in whole pixel increments.

You can scroll an object left and right by setting the x property of the scrollRect Rectangle object. You can scroll an object up and down by setting the y property of the scrollRect Rectangle object. If the display object is rotated 90° and you scroll it left and right, the display object actually scrolls up and down.


Implementation
    public function get scrollRect():Rectangle
    public function set scrollRect(value:Rectangle):void

See also


Example

The following example shows how the scrollRect property defines the scrolling area for a display object, circle. When you click the circle object, the clicked() event handler method adjusts the y property of the scrollRect property of the circle object, causing the object to scroll down:

import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.events.MouseEvent;

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFFCC00);
circle.graphics.drawCircle(200, 200, 200);
circle.scrollRect = new Rectangle(0, 0, 200, 200);
addChild(circle);

circle.addEventListener(MouseEvent.CLICK, clicked);

function clicked(event:MouseEvent):void {
    var rect:Rectangle = event.target.scrollRect;
    rect.y -= 5;
    event.target.scrollRect = rect;
}
stageproperty 
stage:Stage  [read-only]

The Stage of the display object. A Flash application has only one Stage object. For example, you can create and load multiple display objects into the display list, and the stage property of each display object refers to the same Stage object (even if the display object belongs to a loaded SWF file).

If a display object is not added to the display list, its stage property is set to null.


Implementation
    public function get stage():Stage

Example

The following code creates two TextField objects and uses the width property of the Stage object to position the text fields:

import flash.text.TextField;

var tf1:TextField = new TextField();
tf1.text = "Text Field 1";
tf1.border = true;
tf1.x = 10;
addChild(tf1);
tf1.width = tf1.stage.stageWidth / 2 - 10;

var tf2:TextField = new TextField();
tf2.text = "Text Field 2";
tf2.border = true;
tf2.x = tf1.x + tf1.width + 5;
addChild(tf2);
tf2.width = tf2.stage.stageWidth / 2 - 10;

trace(stage.stageWidth);
transformproperty 
transform:Transform  [read-write]

An object with properties pertaining to a display object's matrix, color transform, and pixel bounds. The specific properties — matrix, colorTransform, and three read-only properties (concatenatedMatrix, concatenatedColorTransform, and pixelBounds) — are described in the entry for the Transform class.

Each of the transform object's properties is itself an object. This concept is important because the only way to set new values for the matrix or colorTransform objects is to create a new object and copy that object into the transform.matrix or transform.colorTransform property.

For example, to increase the tx value of a display object's matrix, you must make a copy of the entire matrix object, then copy the new object into the matrix property of the transform object:


    var myMatrix:Object = myDisplayObject.transform.matrix;  
    myMatrix.tx += 10; 
    myDisplayObject.transform.matrix = myMatrix;  
    

You cannot directly set the tx property. The following code has no effect on myDisplayObject:


    myDisplayObject.transform.matrix.tx += 10;
    

You can also copy an entire transform object and assign it to another display object's transform property. For example, the following code copies the entire transform object from myOldDisplayObj to myNewDisplayObj:

myNewDisplayObj.transform = myOldDisplayObj.transform;

The resulting display object, myNewDisplayObj, now has the same values for its matrix, color transform, and pixel bounds as the old display object, myOldDisplayObj.


Implementation
    public function get transform():Transform
    public function set transform(value:Transform):void

See also


Example

The following code sets up a square Sprite object. When the user clicks the sprite, the transformer() method adjusts the colorTransform and matrix properties of the transform property of the sprite:

import flash.display.Sprite;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Transform;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.lineStyle(20, 0xFF2200);
square.graphics.beginFill(0x0000DD);
square.graphics.drawRect(0, 0, 100, 100);
addChild(square);

var resultColorTransform:ColorTransform = new ColorTransform();
resultColorTransform.alphaMultiplier = 0.5;
resultColorTransform.redOffset = 155;
resultColorTransform.greenMultiplier = 0.5;

var skewMatrix:Matrix = new Matrix(1, 1, 0, 1);

square.addEventListener(MouseEvent.CLICK, transformer);

function transformer(event:MouseEvent):void {
    var transformation:Transform = square.transform;
    var tempMatrix:Matrix = square.transform.matrix;
    tempMatrix.concat(skewMatrix);
    square.transform.colorTransform = resultColorTransform;
    
    square.transform.matrix = tempMatrix;
}
visibleproperty 
visible:Boolean  [read-write]

Whether or not the display object is visible. Display objects that are not visible are disabled. For example, if visible=false for an InteractiveObject instance, it cannot be clicked.


Implementation
    public function get visible():Boolean
    public function set visible(value:Boolean):void

Example

The following code uses a Timer object to call a function that periodically changes the visible property of a display object, resulting in a blinking effect:

import flash.text.TextField;
import flash.utils.Timer;
import flash.events.TimerEvent;

var tf:TextField = new TextField();
tf.text = "Hello.";
addChild(tf);

var tim:Timer = new Timer(250);
tim.start();
tim.addEventListener(TimerEvent.TIMER, blinker);

function blinker(event:TimerEvent):void {
    tf.visible = !tf.visible;
}
widthproperty 
width:Number  [read-write]

Indicates the width of the display object, in pixels. The width is calculated based on the bounds of the content of the display object. When you set the width property, the scaleX property is adjusted accordingly, as shown in the following code:

 var rect:Shape = new Shape();
 rect.graphics.beginFill(0xFF0000);
 rect.graphics.drawRect(0, 0, 100, 100);
 trace(rect.scaleX) // 1;
 rect.width = 200;
 trace(rect.scaleX) // 2;

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a width of 0, even if you try to set width to a different value.


Implementation
    public function get width():Number
    public function set width(value:Number):void

Example

The following code sets up a square Sprite object. When the user clicks the sprite, the widen() method increases the width property of the sprite:

import flash.display.Sprite;
import flash.events.MouseEvent;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0, 0, 100, 100);
addChild(square);

square.addEventListener(MouseEvent.CLICK, widen);

function widen(event:MouseEvent):void {
    square.width += 10;
}
xproperty 
x:Number  [read-write]

Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's children inherit a coordinate system that is rotated 90° counterclockwise. The object's coordinates refer to the registration point position.


Implementation
    public function get x():Number
    public function set x(value:Number):void

Example

The following code sets up a circle Sprite object. A Timer object is used to change the x property of the sprite every 50 milliseconds:

import flash.display.Sprite;
import flash.utils.Timer;
import flash.events.TimerEvent;

var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFF0000);
circle.graphics.drawCircle(100, 100, 100);
addChild(circle);

var tim:Timer = new Timer(50);
tim.start();
tim.addEventListener(TimerEvent.TIMER, bounce);

var xInc:Number = 2;

function bounce(event:TimerEvent):void {
    circle.x += xInc;
    if (circle.x > circle.width) {
        xInc = -2;
    }
    if (circle.x < 0) {
        xInc = 2;
    }
}
yproperty 
y:Number  [read-write]

Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's children inherit a coordinate system that is rotated 90° counterclockwise. The object's coordinates refer to the registration point position.


Implementation
    public function get y():Number
    public function set y(value:Number):void

Example

The following code creates two TextField objects and adjusts the height property of each based on the textHeight property of each; it also positions the second text field by setting its y property:
import flash.text.TextField;

var tf1:TextField = new TextField();
tf1.text = "Text Field 1";
tf1.border = true;
tf1.wordWrap = true;
tf1.width = 40;
tf1.height = tf1.textHeight + 5;
addChild(tf1);

var tf2:TextField = new TextField();
tf2.text = "Text Field 2";
tf2.border = true;
tf2.wordWrap = true;
tf2.width = 40;
tf2.height = tf2.textHeight + 5;
tf2.y = tf1.y + tf1.height + 5;
addChild(tf2);
Method Detail
getBounds()method
public function getBounds(targetCoordinateSpace:DisplayObject):Rectangle

Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object. Consider the following code, which shows how the rectangle returned can vary depending on the targetCoordinateSpace parameter that you pass to the method:

     var container:Sprite = new Sprite();
     container.x = 100;
     container.y = 100;
     this.addChild(container);
     var contents:Shape = new Shape();
     contents.graphics.drawCircle(0,0,100);
     container.addChild(contents);
     trace(contents.getBounds(container));
      // (x=-100, y=-100, w=200, h=200)
     trace(contents.getBounds(this));
      // (x=0, y=0, w=200, h=200)
     

Note: Use the localToGlobal() and globalToLocal() methods to convert the display object's local coordinates to display coordinates, or display coordinates to local coordinates, respectively.

The getBounds() method is similar to the getRect() method; however, the Rectangle returned by the getBounds() method includes any strokes on shapes, whereas the Rectangle returned by the getRect() method does not. For an example, see the description of the getRect() method.

Parameters

targetCoordinateSpace:DisplayObject — The display object that defines the coordinate system to use.

Returns
Rectangle — The rectangle that defines the area of the display object relative to the targetCoordinateSpace object's coordinate system.

See also

getRect()method 
public function getRect(targetCoordinateSpace:DisplayObject):Rectangle

Returns a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter, excluding any strokes on shapes. The values that the getRect() method returns are the same or smaller than those returned by the getBounds() method.

Note: Use localToGlobal() and globalToLocal() methods to convert the display object's local coordinates to Stage coordinates, or Stage coordinates to local coordinates, respectively.

Parameters

targetCoordinateSpace:DisplayObject — The display object that defines the coordinate system to use.

Returns
Rectangle — The rectangle that defines the area of the display object relative to the targetCoordinateSpace object's coordinate system.

See also


Example

The following example shows how the getBounds() method can return a larger rectangle than the getRect() method does, because of the additional area taken up by strokes. In this case, the triangle sprite includes extra strokes because of the values passed as the width and jointStyle parameters of the lineStyle() method. The trace() output (in the last two lines) shows the differences between the getRect() and getBounds() rectangles:

import flash.display.CapsStyle;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flash.geom.Rectangle;

var triangle:Sprite = new Sprite();
var color:uint = 0xFF0044;
var lineWidth:Number = 20;
var lineAlpha:Number = 1.0;
var pixelHinting:Boolean = true;
var scaleMode:String = LineScaleMode.NORMAL;
var caps:String = CapsStyle.SQUARE;
var joints:String = JointStyle.MITER;
triangle.graphics.lineStyle(lineWidth, color, lineAlpha, pixelHinting, scaleMode, caps, joints);

var triangleSide:Number = 100;
triangle.graphics.moveTo(0, 0);
triangle.graphics.lineTo(0, triangleSide);
triangle.graphics.lineTo(triangleSide, triangleSide);
triangle.graphics.lineTo(0, 0);

addChild(triangle);

trace(triangle.getBounds(this)); // (x=-10, y=-24.1, w=134.1, h=134.1)
trace(triangle.getRect(this));     // (x=0, y=0, w=100, h=100)
globalToLocal()method 
public function globalToLocal(point:Point):Point

Converts the point object from the Stage (global) coordinates to the display object's (local) coordinates.

To use this method, first create an instance of the Point class. The x and y values that you assign represent global coordinates because they relate to the origin (0,0) of the main display area. Then pass the Point instance as the parameter to the globalToLocal() method. The method returns a new Point object with x and y values that relate to the origin of the display object instead of the origin of the Stage.

Parameters

point:Point — An object created with the Point class. The Point object specifies the x and y coordinates as properties.

Returns
Point — A Point object with coordinates relative to the display object.

See also


Example

The following code creates a Shape object and shows the result of calling the hitTestPoint() method, using different points as parameters. The globalToLocal() method converts the point from Stage coordinates to the coordinate space of the shape:

import flash.display.Shape;
import flash.geom.Point;

var circle:Shape = new Shape();
circle.graphics.beginFill(0x0000FF);
circle.graphics.drawCircle(40, 40, 40);
circle.x = 10;
addChild(circle);

var point1:Point = new Point(0, 0);
trace(circle.hitTestPoint(point1.x, point1.y, true)); // false
trace(circle.hitTestPoint(point1.x, point1.y, false)); // false
trace(circle.globalToLocal(point1)); // [x=-10, y=0]

var point2:Point = new Point(10, 1);
trace(circle.hitTestPoint(point2.x, point2.y, true)); // false
trace(circle.hitTestPoint(point2.x, point2.y, false)); // true
trace(circle.globalToLocal(point2)); // [x=0, y=1]

var point3:Point = new Point(30, 20);
trace(circle.hitTestPoint(point3.x, point3.y, true)); // true
trace(circle.hitTestPoint(point3.x, point3.y, false)); // true
trace(circle.globalToLocal(point3)); // [x=20, y=20]
hitTestObject()method 
public function hitTestObject(obj:DisplayObject):Boolean

Evaluates the display object to see if it overlaps or intersects with the obj display object.

Parameters

obj:DisplayObject — The display object to test against.

Returns
Booleantrue if the display objects intersect; false if not.

Example

The following code creates three Shape objects and shows the result of calling the hitTestObject() method:

import flash.display.Shape;

var circle1:Shape = new Shape();
circle1.graphics.beginFill(0x0000FF);
circle1.graphics.drawCircle(40, 40, 40);
addChild(circle1);

var circle2:Shape = new Shape();
circle2.graphics.beginFill(0x00FF00);
circle2.graphics.drawCircle(40, 40, 40);
circle2.x = 50;
addChild(circle2);

var circle3:Shape = new Shape();
circle3.graphics.beginFill(0xFF0000);
circle3.graphics.drawCircle(40, 40, 40);
circle3.x = 100;
circle3.y = 67;
addChild(circle3);

trace(circle1.hitTestObject(circle2)); // true
trace(circle1.hitTestObject(circle3)); // false
trace(circle2.hitTestObject(circle3)); // true
hitTestPoint()method 
public function hitTestPoint(x:Number, y:Number, shapeFlag:Boolean = false):Boolean

Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters. The x and y parameters specify a point in the coordinate space of the Stage, not the display object container that contains the display object (unless that display object container is the Stage).

Parameters

x:Number — The x coordinate to test against this object.
 
y:Number — The y coordinate to test against this object.
 
shapeFlag:Boolean (default = false) — Whether to check against the actual pixels of the object (true) or the bounding box (false).

Returns
Booleantrue if the display object overlaps or intersects with the specified point; false otherwise.

See also


Example

The following code creates a Shape object and shows the result of calling the hitTestPoint() method, using different points as parameters. The globalToLocal() method converts the point from Stage coordinates to the coordinate space of the shape:

import flash.display.Shape;
import flash.geom.Point;

var circle:Shape = new Shape();
circle.graphics.beginFill(0x0000FF);
circle.graphics.drawCircle(40, 40, 40);
circle.x = 10;
addChild(circle);

var point1:Point = new Point(0, 0);
trace(circle.hitTestPoint(point1.x, point1.y, true)); // false
trace(circle.hitTestPoint(point1.x, point1.y, false)); // false
trace(circle.globalToLocal(point1)); // [x=-10, y=0]

var point2:Point = new Point(10, 1);
trace(circle.hitTestPoint(point2.x, point2.y, true)); // false
trace(circle.hitTestPoint(point2.x, point2.y, false)); // true
trace(circle.globalToLocal(point2)); // [x=0, y=1]

var point3:Point = new Point(30, 20);
trace(circle.hitTestPoint(point3.x, point3.y, true)); // true
trace(circle.hitTestPoint(point3.x, point3.y, false)); // true
trace(circle.globalToLocal(point3)); // [x=20, y=20]
localToGlobal()method 
public function localToGlobal(point:Point):Point

Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.

This method allows you to convert any given x and y coordinates from values that are relative to the origin (0,0) of a specific display object (local coordinates) to values that are relative to the origin of the Stage (global coordinates).

To use this method, first create an instance of the Point class. The x and y values that you assign represent local coordinates because they relate to the origin of the display object.

You then pass the Point instance that you created as the parameter to the localToGlobal() method. The method returns a new Point object with x and y values that relate to the origin of the Stage instead of the origin of the display object.

Parameters

point:Point — The name or identifier of a point created with the Point class, specifying the x and y coordinates as properties.

Returns
Point — A Point object with coordinates relative to the Stage.

See also


Example

The following code creates a Sprite object. The mouseX and mouseY properties of the sprite are in the coordinate space of the display object. This code uses the localToGlobal() method to translate these properties to the global (Stage) coordinates:

import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;

var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFCC00);
square.graphics.drawRect(0, 0, 100, 100);
square.x = 100;
square.y = 200;

addChild(square);

square.addEventListener(MouseEvent.CLICK, traceCoordinates)

function traceCoordinates(event:MouseEvent):void {
    var clickPoint:Point = new Point(square.mouseX, square.mouseY);
    trace("display object coordinates:", clickPoint);
    trace("stage coordinates:", square.localToGlobal(clickPoint));
}
Event Detail
added Event
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.ADDED

Dispatched when a display object is added to the display list. The following methods trigger this event: DisplayObjectContainer.addChild(), DisplayObjectContainer.addChildAt().

The Event.ADDED constant defines the value of the type property of an added event object.

This event has the following properties:

PropertyValue
bubblestrue
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe DisplayObject instance being added to the display list. The target is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.

See also

addedToStage Event  
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.ADDED_TO_STAGE

Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained. The following methods trigger this event: DisplayObjectContainer.addChild(), DisplayObjectContainer.addChildAt().

The Event.ADDED_TO_STAGE constant defines the value of the type property of an addedToStage event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe DisplayObject instance being added to the on stage display list, either directly or through the addition of a sub tree in which the DisplayObject instance is contained. If the DisplayObject instance is being directly added, the added event occurs before this event.

See also

enterFrame Event  
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.ENTER_FRAME

Dispatched when the playhead is entering a new frame. If the playhead is not moving, or if there is only one frame, this event is dispatched continuously in conjunction with the frame rate. This event is dispatched simultaneously to all display objects listenting for this event.

The Event.ENTER_FRAME constant defines the value of the type property of an enterFrame event object.

Note: This event does not go through a "capture phase" and is dispatched directly to the target, whether the target is on the display list or not.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetAny DisplayObject instance with a listener registered for the ENTER_FRAME event.
removed Event  
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.REMOVED

Dispatched when a display object is about to be removed from the display list. Two methods of the DisplayObjectContainer class generate this event: removeChild() and removeChildAt().

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed to make room for the new object: addChild(), addChildAt(), and setChildIndex().

The Event.REMOVED constant defines the value of the type property of a removed event object.

This event has the following properties:

PropertyValue
bubblestrue
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe DisplayObject instance to be removed from the display list. The target is not always the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.
removedFromStage Event  
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.REMOVED_FROM_STAGE

Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained. Two methods of the DisplayObjectContainer class generate this event: removeChild() and removeChildAt().

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed to make room for the new object: addChild(), addChildAt(), and setChildIndex().

The Event.REMOVED_FROM_STAGE constant defines the value of the type property of a removedFromStage event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe DisplayObject instance being removed from the on stage display list, either directly or through the removal of a sub tree in which the DisplayObject instance is contained. If the DisplayObject instance is being directly removed, the removed event occurs before this event.
render Event  
Event Object Type: flash.events.Event
Event.type property = flash.events.Event.RENDER

Dispatched when the display list is about to be updated and rendered. This event provides the last opportunity for objects listening for this event to make changes before the display list is rendered. You must call the invalidate() method of the Stage object each time you want a render event to be dispatched. Render events are dispatched to an object only if there is mutual trust between it and the object that called Stage.invalidate().

Note: This event is not dispatched if the display is not rendering. This is the case when the content is either minimized or obscured.

The Event.RENDER constant defines the value of the type property of a render event object.

Note: This event does not go through a "capture phase" and is dispatched directly to the target, whether the target is on the display list or not.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; the default behavior cannot be canceled.
currentTargetThe object that is actively processing the Event object with an event listener.
targetAny DisplayObject instance with a listener registered for the RENDER event.
Examples How to use examples
DisplayObjectExample.as

The following example uses the DisplayObjectExample class to draw an orange square in the corner of the Stage and then respond to events by displaying text information for each event. This task is accomplished by performing the following steps:
  1. Class properties are declared for the color and size of the square.
  2. The constructor calls the draw() method, which draws an orange square on the Stage at the default coordinates of x = 0, y = 0.
  3. The following event listener methods are attached to the square:
    • addedHandler() listens for added events, dispatched when the square is added to the display list.
    • enterFrameHandler() listens for enterFrame events, which have no real meaning in this example.
    • removedHandler() listens for removed events, dispatched when the square is removed from the display list, which happens when the square is clicked.
    • clickHandler() listens for click events, dispatched when the orange square is clicked.
    • renderHandler() listens for render events after the display list is updated.

package {
    import flash.display.Sprite;

    public class DisplayObjectExample extends Sprite {
        public function DisplayObjectExample() {
            var child:CustomDisplayObject = new CustomDisplayObject();
            addChild(child);
        }
    }
}

import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.*;

class CustomDisplayObject extends Sprite {
    private var bgColor:uint = 0xFFCC00;
    private var size:uint    = 80;

    public function CustomDisplayObject() {
        draw();
        addEventListener(Event.ADDED, addedHandler);
        addEventListener(Event.ENTER_FRAME, enterFrameHandler);
        addEventListener(Event.REMOVED, removedHandler);
        addEventListener(MouseEvent.CLICK, clickHandler);
        addEventListener(Event.RENDER, renderHandler);
    }

    private function draw():void {
        graphics.beginFill(bgColor);
        graphics.drawRect(0, 0, size, size);
        graphics.endFill();
    }

    private function clickHandler(event:MouseEvent):void {
        trace("clickHandler: " + event);
        parent.removeChild(this);
    }

    private function addedHandler(event:Event):void {
        trace("addedHandler: " + event);
        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;
        stage.addEventListener("resize", resizeHandler);
    }

    private function enterFrameHandler(event:Event):void {
        trace("enterFrameHandler: " + event);
        removeEventListener("enterFrame", enterFrameHandler);
    }

    private function removedHandler(event:Event):void {
        trace("removedHandler: " + event);
        stage.removeEventListener("resize", resizeHandler);
    }

    private function renderHandler(event:Event):void {
        trace("renderHandler: " + event);
    }

    private function resizeHandler(event:Event):void {
        trace("resizeHandler: " + event);
    }
}