Answer to Question #81949 in AJAX | JavaScript | HTML | PHP for Alby

Question #81949
So i have a canvas, an image, and a 10 input fields for y and x coordinates. When i press start button the image will move to these coordinates in an animation like movement. How can i do that?
1
Expert's answer
2018-10-15T08:24:09-0400

To smoothly (animated) move image on the canvas you need to write moveImage(startX, startY, stopX, stopY) function.

Function takes start coordinates (from which point start to move image) and stop coordinates (to which point need to move image). As a result function returns promise, which resolves when animation is done.

Example moveImage(10, 10, 50, 50) - moves image 40px to the right and 40px to the left.


Implementation of moveImage function can follow next algorithm:

1 - create promise

2 - start interval (use setInterval) for example with 60 milliseconds

3 - clear canvas (use ctx.clearRect)

4 - draw image (use ctx.drawImage)

5 - move image coordinates (for example by two pixels: x += 2, y += 2)

6 - check if image coordinates within start-stop positions, if yes go to step 3, if not clear interval and resolve promise


To sequentially move image several times by coordinates taken from input fields you need to chain promises returned by function.

The example below moves image form position 0:0 to 10:10, then from 10:10 to 50:50 and finally back from 50:50 to 0:0.

moveImage(0, 0, 10, 10)

.then(() => moveImage(10, 10, 50, 50))

.then(() => moveImage(50, 50, 0, 0));

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS