index.ts1203 chars39 lines
In this example, we create a class called MouseFollower
which handles the logic for following the mouse with an image on the canvas, as well as clearing the canvas on a click event.
The canvas and image elements are passed to the class constructor. We set up mousemove and click event listeners on the canvas and call the loop
method to continuously redraw the image on the canvas with the requestAnimationFrame
function.
The mousemoveHandler
method sets this.x
and this.y
to the current mouse position, adjusted for the position of the canvas and the size of the image so that the image is centered around the mouse cursor.
The clearScreen
method simply clears the entire canvas.
The loop
method clears the canvas, draws the image at the current position, and then sets up the next animation frame. Once the image is loaded, we create a new instance of MouseFollower
and pass the canvas and image elements to it.
gistlibby LogSnag