Reputation: 149
I'm making a dragged image. It works as it should. I also have buttons that scale the image. after scaling, the drug works but it cuts the position. I can't find the right words to describe this behavior.At the first movement the image changes its position slightly
what calculations do I need to do too. to get a smooth drag, after scaling an element.
https://codesandbox.io/s/laughing-tree-1zqhf?file=/src/App.js
Thank you in advance
Upvotes: 1
Views: 247
Reputation: 1001
You have to keep the initial X and calculate only the moved difference.
const onMouseDown = e => {
e.persist();
var initialX = e.pageX;
const onMouseMove = ev => {
var newX = initialX - ev.pageX;
setX(x - newX);
};
const onMouseUp = () => {
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
};
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
};
Link to forked sandbox: https://codesandbox.io/s/compassionate-ishizaka-kvmnk?file=/src/App.js
Upvotes: 1