justing just typescript no dependencies a cat image that follows your mouse around the screen. clicking clears the screen. in typescript

index.ts
class MouseFollower {
  private canvas: HTMLCanvasElement;
  private img: HTMLImageElement;
  private ctx: CanvasRenderingContext2D;
  private x: number;
  private y: number;

  constructor(canvas: HTMLCanvasElement, img: HTMLImageElement) {
    this.canvas = canvas;
    this.img = img;
    this.ctx = this.canvas.getContext("2d");
    this.x = 0;
    this.y = 0;
    this.canvas.addEventListener("mousemove", this.mousemoveHandler.bind(this));
    this.canvas.addEventListener("click", this.clearScreen.bind(this));
    this.loop();
  }

  private mousemoveHandler(event: MouseEvent) {
    this.x = event.clientX - this.canvas.offsetLeft - this.img.width / 2;
    this.y = event.clientY - this.canvas.offsetTop - this.img.height / 2;
  }

  private clearScreen() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }

  private loop() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.drawImage(this.img, this.x, this.y);
    requestAnimationFrame(this.loop.bind(this));
  }
}

const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const img = new Image();
img.src = "cat.png";
img.onload = () => new MouseFollower(canvas, img);
1203 chars
39 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