Currently, I am struggling with the task of centering my image based on the touch input that will drag it. For example, if the user touches the top right corner of the image, I want the image to automatically move so that its center aligns with that touch point.
The code snippet I have tried to achieve this is as follows:
img.style.left = e.touches[0].clientX + "px";
img.style.top = e.touches[0].clientX - shiftX + "px";
Unfortunately, the above code is not working as expected.
Below is the complete code for the touch start event:
img.addEventListener('touchstart', function(e) {
beingDragged = img;
start = e.target.parentNode.id;
img.style.zIndex = 1;
shiftX = e.touches[0].clientX - (img.width/2);
shiftY = e.touches[0].clientY - (img.height/2); //code for dragging the image in the later touchmove event
img.style.left = e.touches[0].clientX + "px";
img.style.top = e.touches[0].clientY + "px";
});
I have attempted to address this issue by using the shift values in the touchmove event as well as the bounding client rectangle, but none of these solutions have worked.
The touch move function itself works correctly, but I am focused on fixing this minor issue with the touchstart event.
Below is the CSS for the image:
img {
position: absolute;
width: 90%;
height: 90%;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
In response to feedback, I tried to replicate and solve this error on a smaller scale, but when implementing the solution in the main code, the image gets flung off the screen.