javascripthtml5-canvasaddchild

Clone items when clicked (Html5-canvas)


I'm new with html5-canvas and I'm facing some problems. The code below will clone an object when is clicked on it and it can be dragged too. But it only works once, and when I click the object again the clone will move back to its original origin. How can I clone multiple times every time i click on it? and make the clone stay where it is when dragged.

Here's a preview

item = new lib.item104();

this.addChild(item);
item.x = 250;
item.y = 350;
item.scaleX = item.scaleY = 1;

var Clone;
Clone = new lib.anim104();

item.addEventListener("click", itemPressed.bind(this));
function itemPressed(evt) {
    this.addChild(Clone);
    Clone.x = 250;
    Clone.y = 200;
    Clone.scaleX = Clone.scaleY = 1.5;
}

Clone.addEventListener("pressmove", dragClone.bind(this));
function dragClone(evt) {
    var p = this.globalToLocal(evt.stageX, evt.stageY);
    evt.currentTarget.x = p.x;
    evt.currentTarget.y = p.y;
}

Solution

  • I can't test this since I don't have your context, but I think all you need to do is put all the code dealing with the Clone inside the event listener, something like what I've done below.

    This way, each event will create a new copy of Clone, and the conflicts you were experiencing should disappear.

    item = new lib.item104();
    
    this.addChild(item);
    item.x = 250;
    item.y = 350;
    item.scaleX = item.scaleY = 1;
    
    item.addEventListener("click", itemPressed.bind(this));
    
    function itemPressed(evt) {
      var Clone;
      Clone = new lib.anim104();
    
      this.addChild(Clone);
      Clone.x = 250;
      Clone.y = 200;
      Clone.scaleX = Clone.scaleY = 1.5;
      Clone.addEventListener("pressmove", dragClone.bind(this));
    }
    
    function dragClone(evt) {
      var p = this.globalToLocal(evt.stageX, evt.stageY);
      evt.currentTarget.x = p.x;
      evt.currentTarget.y = p.y;
    }