views:

137

answers:

1

I want MyCanvas to draw lines on itself, but they seem to be drawn behind the background. What's going on and how should I do this?

Main.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:my="*">
    <my:MyCanvas width="300" height="300" id="myCanvas"></my:MyCanvas>
    <mx:Button label="Draw" click="myCanvas.Draw();"></mx:Button>
</mx:Application>

MyCanvas.as

package  
{
    import mx.containers.Canvas;
    public class MyCanvas extends Canvas
    {
        public function MyCanvas() 
        {
            this.setStyle("backgroundColor", "white");
        }
        public function Draw():void
        {
            graphics.lineStyle(1);
            graphics.moveTo( -10, -10);
            graphics.lineTo(width + 10, height + 10);
        }
    }
}

Thanks.

+1  A: 

The Graphics object of the DisplayObject itself is always positioned at the bottom of the DisplayList. In this case it is possible that an overlapping child is added by the superclass, perhaps when you apply the white background (not sure I'm not Flex expert).

However it may be safer to try to add a specifically dedicated child to draw into. This way you can have more control over its visibility :

package  
{
    import mx.containers.Canvas;
    public class MyCanvas extends Canvas
    {

        private var shape:Shape;

        public function MyCanvas() 
        {
            this.setStyle("backgroundColor", "white");

            addChild(shape = new Shape());
        }
        public function Draw():void
        {

            shape.graphics.lineStyle(1);
            shape.graphics.moveTo( -10, -10);
            shape.graphics.lineTo(width + 10, height + 10);
        }
    }
}
Theo.T
Thanks.Line "addChild(shape = new Shape());" needs to be changed to "rawChildren.addChild(shape = new Shape());"
mauvo
It should be noted that best practices for the flex3 sdk == adding children in the createChildren() method. override protected function createChildren(), let the inherited classes do their thing by 'supering' first (99% of the time), then addChild.
jeremy.mooer