If you are using jQuery touchend events, the layerX and layerY attributes provide the relative x and y, but do not take into account the transform. So I manually applied the transform by grabbing the transform scale values from the css.
e = the touchend event from jQuery
parent = the jQuery object of the parent element where the "transform" is applied. For me it was $(e.target.parentNode);
const layerX = e.originalEvent.layerX;
const layerY = e.originalEvent.layerY;
const currentScale = 1 / parseFloat(parent.css('transform').match(/-?[\d\.]+/g)[0]);
const offsetX = layerX * currentScale;
const offsetY = layerY * currentScale;
To make the last two lines compatible with touch and click events:
const offsetX = e.offsetX || layerX * currentScaleX;
const offsetY = e.offsetY || layerY * currentScaleY;
Reference for grabbing transform values: Fetch the css value of transform directly using jquery
If you are using Reactjs onClick
then you can get the layerX and layerY values with: e.nativeEvent.layerX
. For some reason the layerX and layerY are not available on the React touch events. If you do need to use the React onTouchEnd
:
const rect = e.nativeEvent.target.getBoundingClientRect();
const layerX = e.changedTouches[0].clientX - rect.left;
const layerY = e.changedTouches[0].clientY - rect.top;
const currentScale = 1 / parseFloat(parent.css('transform').match(/-?[\d\.]+/g)[0]);
const offsetX = layerX * currentScale;
const offsetY = layerY * currentScale;
Note: It is better to store the values of the transform in Redux rather than grabbing them with jQuery.