Mask problem with flex canvas and drag & drop

July 12th, 2009 by Andrea Franz

Some weeks ago a spent a lot of time trying to fix a bug inside an AIR application I was working on.
I wrote a custom component that has an image as child. This image is draggable, and the container should act as a mask. The problem was that when I started dragging the picture, the picture went outside its container, like the following example.

Try dragging the red square outside the white one:

This movie requires Flash Player 9

I fixed this bug just setting the scrollRect property to the container:

This movie requires Flash Player 9

Only when I realized how to fix the bug I found another guy with the same problem and the same solution.

Here the code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application width="500" height="300" xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="vertical" verticalAlign="middle" horizontalAlign="center"
  applicationComplete="init()">
  <mx:Script>
    <![CDATA[												
      public function init():void
      {				
        this.container.scrollRect = new Rectangle(0, 0, this.container.width, this.container.height);																
        this.draggableCanvas.addEventListener(MouseEvent.MOUSE_UP, this.mouseUpHandler);				
        this.draggableCanvas.addEventListener(MouseEvent.MOUSE_DOWN, this.mouseDownHandler);
      }			
 
      private function mouseDownHandler(event:MouseEvent):void
      {
        this.draggableCanvas.startDrag();
      }
 
      private function mouseUpHandler(event:MouseEvent):void
      {
        this.draggableCanvas.stopDrag();
        }
    ]]>
  </mx:Script>
  <mx:Canvas id="container" width="300" height="250" backgroundColor="white" horizontalScrollPolicy="off" verticalScrollPolicy="off">
    <mx:Canvas id="draggableCanvas" x="50" y="25" width="200" height="200" backgroundColor="#AA0000">			
    </mx:Canvas>
  </mx:Canvas>
</mx:Application>