Question

I am trying to accomplish what is in theory simple..

I have a stage.. if the stage is empty a click on the stage places a layer with a circle object on the stage.. (I have a working code for this..)

If layer and object already exist on stage I would like to MOVE them to an x and y position..

I am unclear on whether it is better to destroy the object and create a new one or I can set X and Y and redraw ...

I tried both but I am not getting something right..

// 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();
    }
Was it helpful?

Solution

You will save resources and gain performance by reusing your existing circle rather than destroying and recreating a new circle.

You have a scoping issue in your code.

Since you're creating var circle inside your if statement, that circle variable is lost after the if completes.

You have several ways of "remembering" the circle.

The easiest way is simply declare var circle globally (outside and before the if statement).

You can also give the circle an id and later ask the layer to fetch the object with that 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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top