2013-10-28 97 views
1

我要完成的任务是在理论上很简单..KineticJS,移动形状和REMOVE形状

我有一个阶段..如果舞台是空舞台上的点击放置一个层上一个圆圈对象舞台..(我有一个工作代码,这个..)

如果图层和对象在舞台上已经存在,我想将它们移动到x和y位置..

我是否还不清楚最好销毁对象并创建一个新对象,或者我可以设置X和Y并重新绘制...

我都尝试,但我没有得到正确的事情..

// I have a working code here that detects mouseX and mouseY position 

// Detecting if object exists (works fine) 
    var theSpot = stage.find('.click_spot'); 

    if (theSpot[0] === undefined) {   
     //alert('Object not found, create a new one...'); 

     var layer = new Kinetic.Layer(); 
     var circle = new Kinetic.Circle({ 
      x: mouseX, 
      y: mouseY, 
      radius: 30, 
      fill: 'red', 
      stroke: 'black', 
      strokeWidth: 1, 
      draggable: true, 
      name:'click_spot' 
     }); 

     layer.add(circle); 
     stage.add(layer); 

    } else { 

// Move the object OR remove and draw a new one 
// when I try to remove,, circle.remove(); does not remove it 

     //alert('Object found, move it to new x, y location'); 

     circle.setX(mouseX); // I tried inserting values directly as well 
     circle.setY(mouseY); // circle.setX(15) and circle.setX(15) but no joy... 
     layer.draw(); 
    } 

回答

2

您将节省资源,并通过重用现有的圈子,而不是破坏并重新创建一个新的圈子获得性能。

您在代码中有一个范围问题。

由于您在if语句中创建var circle,因此if完成后该圆圈变量将丢失。

你有几种“记住”圆的方法。

最简单的方法是简单地声明var circle全局(外部和if语句之前)。

你也可以给圆一个id,后来问层取得与该ID的对象:

var circle = new Kinetic.Circle({ 
     id="myCircle", 
     x: mouseX, 
     y: mouseY, 
     radius: 30, 
     fill: 'red', 
     stroke: 'black', 
     strokeWidth: 1, 
     draggable: true, 
     name:'click_spot' 
    }); 

    // get the object by its id 

    var myCircle = layer.get("#myCircle"); 

    // then you can use this reference to make your changes 

    myCircle.setX(mouseX); 
    myCircle.setY(mouseY); 
    layer.draw(); 
+0

谢谢坊间..我很欣赏这个..你的建议帮我解决这个问题和其他一些问题..我在操纵它的位置之前创建了一个圆圈,而不是销毁和重新创建,我基本上隐藏并在需要时显示它。我仍然有一些问题需要实际删除不需要的对象,但这是一个单独的问题,如果我无法弄清楚,我会单独询问。 – GRowing