Though the solution provided by @olsn most certainly works, using the regX/regY to offset the object to account for the current mouse position might lead to difficulties when subsequently transforming the object.
E.g. if you want to rotate the object around its center, you will want to have the regX/regY reset to object width/2 and object height/2. This will reintroduce the glitch, though at a later stage in your object manipulation.
Given scenarios like this, I like to prevent using regX/regY to prevent dragging glitches.
Alternatively, I take note of the mouse position on dragstart
, and measure the mouse movement while dragging
. By applying this movement to the objects x/y position, the object will appear to move with the mouse, simulating dragging.
As shown in this fiddle and in the following code:
function enableDrag(obj) {
obj.on("mousedown", dragstart);
obj.on("pressmove", drag);
};
function dragstart(evt) {
dragging = false;
}
function drag(evt) {
// register object starting point and mousedrag (stage) starting point
if (!dragging || !dragging.startCoords || !dragging.stageCoords) {
dragging = evt.currentTarget;
dragging.startCoords = {x: dragging.x, y: dragging.y};
dragging.stageCoords = {x: evt.stageX, y: evt.stageY};
}
// calculate mouse offset after move, relative to starting point, subtract this movement from object coords (move)
dragging.stageMove = {x: dragging.stageCoords.x - evt.stageX, y: dragging.stageCoords.y - evt.stageY};
dragging.objectMove = {x: dragging.startCoords.x - dragging.stageMove.x, y: dragging.startCoords.y - dragging.stageMove.y};
// apply movement to object
evt.currentTarget.x = dragging.objectMove.x;
evt.currentTarget.y = dragging.objectMove.y;
stage.update(); //update stage without passing through ticker for higher FPS
}