+ 1

How can a canvas element move to a coordinate?

I know how to do the animation and rendering. The math is what I need. A canvas element is at a point. A target coordinate is at another point. How can I make the element move as linearly to the other target point as possible? The element's movement should be animated. The speed should be constant.

4th Nov 2018, 12:15 AM
Nick
Nick - avatar
6 odpowiedzi
+ 2
I'm not an expert when it comes down to working with a canvas, and maybe there is an easier solution, but mathematically I would begin by calculating the vector from your current point C to the target point T (T - C). This vector is the line your element will follow on its way (linear movement). Afterwards, for the speed, I'd calculate the length of the vector, which is the distance your element will travel, and divide the x and y value of T by that length. Then you multiply these two values by the factor 'speed'. Once you have done that, you can add the two values to your element's x and y value each iteration, and voila, your element travels linearly to its destination with the speed you want it to. I hope this was understandable (and moreover correct)! 😬
4th Nov 2018, 12:47 AM
Shadow
Shadow - avatar
+ 2
No problem, Nick, but you better try this out before anything else, because I'm only theoretically assuming it to work, I didn't test it. 😅 [EDIT] I made a mistake above, you don't have to divide the x and y value of the target point T by the vector's length, but the x and y value of the vector by its length. My bad, sorry!
4th Nov 2018, 1:01 AM
Shadow
Shadow - avatar
+ 2
Seems valid, Nick, just one thing that I discovered. Try adding console.log("tx = " + tx + ", x = " + x); to your logging. Often, the two won't be equal, simply because the distance traveled is often not perfectly divisible by the speed. You could run a test in each iteration checking if the length of vector CT is bigger than your speed, and if not, set the x and y value of the box to tx and ty. That should make it truly accurate.
4th Nov 2018, 5:32 PM
Shadow
Shadow - avatar
+ 1
This is really helpful, Shadow. Thank you for this explanation :)
4th Nov 2018, 12:55 AM
Nick
Nick - avatar
+ 1
Shadow I tested it out here: https://code.sololearn.com/WkL344jTACgT/?ref=app I think it seems accurate. Is that the correct implementation?
4th Nov 2018, 3:34 PM
Nick
Nick - avatar
+ 1
Shadow Ok, I see what you mean. Thanks for the help :)
5th Nov 2018, 11:52 AM
Nick
Nick - avatar