0

我正在学习一本书中 Actionscript 教室的第 4 课示例,但通过在舞台上添加一个 CLEAR 按钮来修改它。

每当我测试所有功能时,我都可以在按钮顶部进行绘制。理想情况下,当用户绘制时,颜色应该位于按钮下方。

在时间轴中,我有背景层、按钮层和动作层。我在下面添加了代码以帮助更快地解决问题。谢谢!

package  {

import flash.display.MovieClip;

    public class Ellipse extends MovieClip {

        // constructor
        public function Ellipse(w:Number=40,h:Number=40,color:Number=0xff0000) {
            graphics.beginFill(color);
            graphics.drawEllipse(0, 0, w, h);
            graphics.endFill();
        }

    } // end class Ellipse

} // end package




import flash.events.MouseEvent;

var color:Number;
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);

function startDrawing(e:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_MOVE, makeShapes);
color = Math.random() * 0xFFFFFF;
}

function stopDrawing(e:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, makeShapes);
}

function makeShapes(e:MouseEvent):void {
var ellipse:Ellipse = new Ellipse(10, 10, color);
stage.addChild(ellipse);
ellipse.x = mouseX;
ellipse.y = mouseY;
}


btnClear.addEventListener(MouseEvent.CLICK, clearBoard);

function clearBoard(e:MouseEvent)
{
    for (var i:int = stage.numChildren-1; i >= 1; i--) {
   stage.removeChildAt (i);
}
}
4

1 回答 1

0

addChild将项目添加到显示列表的顶部,因此当您将椭圆添加到舞台时,您会将它们添加到按钮和电影的前面。也就是说,您的电影(带有按钮)位于索引 0 处,但您的形状添加到索引 1 或更高处。一种解决方案是将它们添加到电影下方,使用addChildAt

var shapeIndex:uint = 0;
function makeShapes(e:MouseEvent):void {
    var ellipse:Ellipse = new Ellipse(10, 10, color);
    stage.addChildAt(ellipse, shapeIndex); // add the shape starting at 0, and count up from there
    // this will keep the movie at the top of the stage's display list
    shapeIndex++;
    ellipse.x = mouseX;
    ellipse.y = mouseY;
}

另一种解决方案是首先制作一个容器剪辑,然后将形状添加到此容器剪辑中。这使您可以轻松控制形状出现的位置:

var container : Sprite = new Sprite();
stage.addChildAt(container, 0); // add the container to the bottom of the stage
// now we can just easily add our shapes to the container, and they will all be behind the main movie.
function makeShapes(e:MouseEvent):void {
    var ellipse:Ellipse = new Ellipse(10, 10, color);
    container.addChild(ellipse);
    shapeIndex++;
    ellipse.x = mouseX;
    ellipse.y = mouseY;
}

这实际上使其他事情变得更容易,例如清除屏幕。您可以简单地删除并重新创建容器剪辑:

function clearBoard(e:MouseEvent)
{
    stage.removeChild(container);
    container = new Sprite();
    stage.addChildAt(container, 0);
}
于 2013-03-20T21:54:03.633 回答