2

Is it possible to move an image inside a canvas element smoothly? this is what I'm trying:

if (a == 1) { // onmousedown
    CX = event.clientX;
    CY = event.clientY;
    return;
} else if (a == 2) { // onmouseup
    CimgX += event.clientX - CX;
    CimgY += event.clientY - CY;
    ctx[0].clearRect(0, 0, canvas[0].width, canvas[0].height);
    ctx[0].drawImage(img, CimgX, CimgY);

but you can see that it won't work smoothly, it will just clear the canvas and draw the image in a new location, I tried onmousemove and setInterval but it didn't work. Any thoughts?

  • After mouseup (or mouseout), you can interpolate waypoints along a line between the mousedown and mouseup points. Then use `requestAnimationFrame` to smoothly move your image along the interpolated waypoints. – markE Mar 11 '16 at 15:10
  • Thanks, but as long as I'm understanding correctly, it will work after `onmouseup` (?) which is not what I want (as the cursor moves). –  Mar 11 '16 at 15:22
  • 1
    Your existing code triggers the move after mouseup so I thought that's what you wanted. :-p To move the image while the mouse is moving you must listen for `mousemove` events and incrementally move your image based on the distance the mouse has moved between each mousemove event. Here is a [previous Q&A](http://stackoverflow.com/questions/32407364/in-html5-javascript-is-there-a-way-to-make-a-polygon-i-just-draw-draggable-or) with an explanation and example code. – markE Mar 11 '16 at 15:30
  • 1
    Thanks, I managed to solve it. I just needed a confirmation that it was possible because I tried and failed and didn't want to waste my time trying to solve a problem I'm not sure it's solvable. –  Mar 12 '16 at 00:06

0 Answers0