Using Draggable I'm allowing users to drag an item from a sidebar into a canvas element in the center of the screen. I have code in place that only allows users to drop an item once it has entered a specific drop target, otherwise it returns to its start position. The canvas is a static size meaning that the size of a users browser window will alter how far an item has to be dragged before it is in the drop target (e.g. at smaller viewports you might only need to drag 50px to the right to hit the drop target but larger viewports that might be 200px).
After an item has been successfully dropped I need to get the X and Y co-ordinates of the dropped item in relation to the drop target. For example, if I dropped in the very top left corner of the drop target, I expect the X and Y to be 0, 0. When logging the onDragEnd event I get multiple variations of X and Y values (clientX, clientY, layerX, layerY, movementX, movementY, offsetX, offsetY, pageX, pageY, screenX, screenY, x, y) but none are giving me what I want.
I was wondering if there is an out-of-the-box method for retrieving this data or whether I'll need to work it out manually based on the position and size of my drop target?
const that = this;
const overlapThreshold = '100%';
let startX;
let startY;
const canvas = document.getElementById('canvas');
Draggable.create('#draggable-player svg', {
// When initially pressing we want to record the start co-ordinates
onPress() {
startX = this.x;
startY = this.y;
},
onDragStart() {
that.setState({ dragging: true });
this.target.classList.add('dragging');
},
onDrag() {
if (this.hitTest(canvas, overlapThreshold)) {
that.setState({ validDrop: true });
this.target.classList.add('valid-drop');
} else {
that.setState({ validDrop: false });
this.target.classList.remove('valid-drop');
}
},
onDragEnd(e) {
console.log(e);
if (that.state.validDrop === true) {
that.addNewItem(e, items.PLAYER, e.x, e.y);
} else {
// If it isn't in the drop area send it back to starting position
TweenLite.to(this.target, 0.2, {
x: startX,
y: startY,
});
}
that.setState({ dragging: false, validDrop: false });
this.target.classList.remove('dragging');
},
});