Skip to main content
Known Participant
July 16, 2020
Answered

How do you make a draggable object? (in html5 canvas)

  • July 16, 2020
  • 1 reply
  • 833 views

Nothing fancy. 

 

Can someone please help me make a rectangle that a user can click on and move it around.

And it stays where the user moved it after they stop moving it. 

 

That's it. 

 

Reading other tutorials, this appears to require either learning spanish, or getting a degree in computer science. 

I've just spent 4 hours trying to figure this out, and I am about to give up. 

    This topic has been closed for replies.
    Correct answer JoãoCésar17023019

    Hi.

     

    Supposing:

    - It's HTML5 Canvas;

    - The Transformation Point of the rec is at the center;

    - The rec is in the main timeline...

     

    ... this code should do the job:

    var root = this;
    var rec = root.rec;
    
    createjs.Touch.enable(stage);
    
    rec.on("mousedown", function(e)
    {
    	e.currentTarget.offsetX = stage.mouseX / stage.scaleX - e.currentTarget.x;
    	e.currentTarget.offsetY = stage.mouseY / stage.scaleY - e.currentTarget.y;
    });
    
    rec.on("pressmove", function(e)
    {
    	e.currentTarget.x = stage.mouseX / stage.scaleX - e.currentTarget.offsetX;
    	e.currentTarget.y = stage.mouseY / stage.scaleY - e.currentTarget.offsetY;
    });

     

    Please let us know.

     

    Regards,

    JC

    1 reply

    JoãoCésar17023019
    Community Expert
    JoãoCésar17023019Community ExpertCorrect answer
    Community Expert
    July 16, 2020

    Hi.

     

    Supposing:

    - It's HTML5 Canvas;

    - The Transformation Point of the rec is at the center;

    - The rec is in the main timeline...

     

    ... this code should do the job:

    var root = this;
    var rec = root.rec;
    
    createjs.Touch.enable(stage);
    
    rec.on("mousedown", function(e)
    {
    	e.currentTarget.offsetX = stage.mouseX / stage.scaleX - e.currentTarget.x;
    	e.currentTarget.offsetY = stage.mouseY / stage.scaleY - e.currentTarget.y;
    });
    
    rec.on("pressmove", function(e)
    {
    	e.currentTarget.x = stage.mouseX / stage.scaleX - e.currentTarget.offsetX;
    	e.currentTarget.y = stage.mouseY / stage.scaleY - e.currentTarget.offsetY;
    });

     

    Please let us know.

     

    Regards,

    JC

    joefreshyAuthor
    Known Participant
    July 16, 2020

    It worked!

     

     

    This is perfect, so many ideas!

    Thank you!

    JoãoCésar17023019
    Community Expert
    Community Expert
    July 16, 2020

    Amazing! You're welcome!

     

    And thanks for the preview!

     

     

    Regards,

    JC