How to restrict the drag and drop area in a canvas

2019-05-19 08:11发布

I have a canvas,lets say of dimensions 500x600.I have some controls inside that canvas.User can rearrange the controls by drag and drop.But I want to restrict the drag and drop within that canvas.

For example:There is a button in the canvas.User can drag and drop the button anywhere inside the canvas.But if the user tries to drag the button out of the canvas boundaries,it should stick in the canvas boundary.

How to achieve this?

2条回答
叛逆
2楼-- · 2019-05-19 08:21

The signature for startDrag() is public function startDrag(lockCenter:Boolean = false, bounds:Rectangle = null):void

The second parameter allows you to pass a Rectangle to act as bounds for your DisplayObject. It won't be dragged outside of this

查看更多
We Are One
3楼-- · 2019-05-19 08:34

You should catch MouseDown event on the target controls and then subscribe MouseMove event. In MouseMove handler you should get Canvas and control's rectangles (in the same coordinate space) and use containsRect() method (documentation is here) to determine if control is still within Canvas. If it goes out you shouldn't move it.

And don't remember unsubscribe your MouseMove event on MouseUp!

查看更多
登录 后发表回答