我只是想让图像在指定的画布区域内移动。如果鼠标光标移出画布区域,图像应该回到原来的位置。下面是我尝试过的代码。
<mx:Script>
<![CDATA[
import mx.controls.Image;
import mx.containers.Canvas;
import flash.geom.Rectangle;
/* [Embed(source="cards/2C.png")]
private var pic:Class; */
public var points:Point;
public var clan:Canvas;
public var offset_x:int;
public var offset_y:int;
public var dropIndex:int=-1;
public var img:Image;
public var dragImage:Image;
public var myImage:Image;
public var doDrag:Boolean;
public var acceptDrag:Boolean;
public function init():void
{
myImage = new Image();
clan = new Canvas();
clan.width=400;
clan.height=300;
clan.x=200;
clan.y=150;
clan.setStyle("backgroundColor",0xcfdccc);
addChild(clan);
myImage.source= pic.pic1;
clan.addChild(myImage);
myImage.addEventListener(MouseEvent.MOUSE_DOWN, ondown);
myImage.addEventListener(MouseEvent.MOUSE_MOVE, mm);
}
public function ondown(event:MouseEvent):void
{
doDrag=true;
return;
}
public function mm(event:MouseEvent):void
{
if(doDrag==true)
{
points = new Point();
myImage.source=event.target.source;
points.x=event.target.x;
points.y=event.target.y;
points=localToGlobal(points);
dragImage = mx.controls.Image(event.target);
myImage.x=points.x;
myImage.y=points.y;
trace(points);
var mywidth:int=clan.width-myImage.width;
var myheight:int=clan.height-myImage.height;
var boundar:flash.geom.Rectangle=new Rectangle(offset_x, offset_y ,mywidth,myheight);
myImage.startDrag(false, boundar);
myImage.addEventListener(MouseEvent.MOUSE_MOVE, onmove);
myImage.addEventListener(MouseEvent.CLICK, onup);
event.updateAfterEvent();
}
}
public function onmove(event:MouseEvent):void
{
if(doDrag)
{
// myImage = new Image();
clan = new Canvas();
var diff:Number = NaN;
var doIncrement:Boolean=false;
var point2:flash.geom.Point= new Point();
img=mx.controls.Image(event.target);
point2.x=this.x;
point2.y=this.y;
point2=globalToLocal(point2);
trace("point2="+ point2);
diff=points.x;
/* trace(stage.x);
trace(stage.y); */
points.x=img.x;
points.y=img.y;
points=globalToLocal(points);
diff=points.x;
trace("points.x="+points.x);
trace("diff: "+ diff);
trace("dropIndex: "+ dropIndex);
if(diff >=0)
{
dropIndex=Math.floor(points.x / offset_x);
doIncrement=true;
trace("dropIndex1: "+ dropIndex);
}
else
{
dropIndex=Math.floor(points.x / offset_x);
}
if(doIncrement)
{
dropIndex++;
}
if(dropIndex >= 0)
{
acceptDrag = true;
}
else if (dropIndex >= -5 && dropIndex <= -1)
{
dropIndex = 0;
acceptDrag = true;
}
}
}
public function onup(event:MouseEvent):void
{
doDrag=false;
img.stopDrag();
acceptDrag=false;
}
]]>
</mx:Script>