|
Fading objects with actionscript code While working with movie clips on stage, we you might want to fade the movie clip in or out instead of toggling its _visible property. There are two procedures to animate a movie clip - By using 'onEnterFrame' event handler
- By using 'set interval()' function
First of all, we will need to create a movie clip, follow the steps below to do the same - Create a new Flash document called fade.fla.
- Draw some graphics on the Stage using the drawing tools, or import an image to the Stage (File > Import > Import to Stage).
- Select the content on the Stage and select Modify > Convert to Symbol.
- Select the Movie clip option and click OK to create the symbol.
- Select the movie clip instance on the Stage and type img1_mc in the Instance Name text box in the Property inspector.
- Select Frame 1 of the Timeline, and add 'onEnterFrame' event handler code or 'set interval()' function in the Actions panel. Code for both is given below
onEnterFrame event handler code - img1_mc.onEnterFrame = function() { img1_mc._alpha -= 5; if (img1_mc._alpha <= 0) { img1_mc._visible = false; delete img1_mc.onEnterFrame; } }; |
set interval() function code - var alpha_interval:Number = setInterval(fadeImage, 50, img1_mc); function fadeImage(target_mc:MovieClip):Void { target_mc._alpha -= 5; if (target_mc._alpha <= 0) { target_mc._visible = false; clearInterval(alpha_interval); cx} } |
- Select Control > Test Movie to test the document.
The movie clip you added to the Stage slowly fades out.
onEnterFrame event handler code explanation- onEnterFrame event handler code is invoked repeatedly at the frame rate of the SWF file. The number of times per second that the event handler is called depends on the frame rate at which the Flash document is set. If the frame rate is 12 frames per second (fps), the onEnterFrame event handler is invoked 12 times per second. Likewise, if the Flash document's frame rate is 30 fps, the event handler is invoked 30 times per second.
setinterval() function explanation- The setInterval() function behaves slightly differently than the onEnterFrame event handler, because the setInterval() function tells Flash precisely how frequently the code should call a particular function. In this code example, the user-defined fadeImage() function is called every 50 milliseconds (20 times per second). The fadeImage() function decrements the value of the current movie clip's _alpha property. When the _alpha value is equal to or less than 0, the interval is cleared, which causes the fadeImage() function to stop executing. Click here to download onEnterFrame event handler code example
Tags: action script fade image tutorial, setinterval(), alpha code
|