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));
Comments
Leave a comment