The last demo looked at displaying more than one item at once, now it’s time to make things move! This demo is pretty simple, the canvas is updated every 20ms and when it’s updated the circle moves towards the mouse cursor. Click the image below to try it out, don’t forget to press the ‘start’ button to, well, make it start!
Below, I’ve included the source code of the demo. You can have a look through all of the code properly on GitHub, but I’ll give a quick overview.
The init function creates the circle and adds it to the canvas, as well as adding an event listener for the mouse move event on the canvas. The canvasOnMouseMove method is called every time the mouse moves over the canvas, this method sets the target position of the circle; i.e the point that it’s aiming to get to. The update method updates the canvas and moves the circle 5% of the way towards the target position, by moving the circle 5% on every update it creates a smooth ease towards the mouse position.
The start method sets an interval for calling the update method, this interval is cleared using the stop method. The reset method is simply there to reset the circle to the center of the canvas. You can grab the source code from GitHub and have a play.