Hobbyist
Hobbyist

Reputation: 16182

Javascript "dragging" an image across a canvas

There's quite a few questions about this where the solution provided is to just set the top left and top down values of the image to the position of the mouse/touch, however what I want to do is to have an actual dragging movement. Regardless as to where on the canvas I press, if I drag my finger to the right x pixels, I want the image to move to the right x pixels. Same goes with left, up, and down.

I'm at a complete loss as to where to even start with this. I will be handling mobile touch events, so I feel like using canvas.addEventListener('touchmove') would be the best option, but I'm not sure.

I already have the canvas repainting and everything handled, just really need help with the logic for dragging the image in real time, instead of just snapping it into position.

Upvotes: 0

Views: 65

Answers (1)

Iansen
Iansen

Reputation: 1268

Get the point where the interaction starts (touchstart) and use it to calculate how much the finger moved on the screen (in the touchmove callback) and add it to the image position (also in touchmove).

PS: Also I recommend using something like PIXI JS for canvas/WebGL stuff ... unless you need a custom solution.

Upvotes: 1

Related Questions