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

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Follow Cat</title>
    <style>
      body {
        cursor: none;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="index.ts"></script>
  </body>
</html>
336 chars
20 lines
index.ts
// index.ts
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

interface Cat {
  x: number;
  y: number;
  image: HTMLImageElement;
  update: (x: number, y: number) => void;
  draw: () => void;
}

class CatImpl implements Cat {
  public x: number;
  public y: number;
  public image: HTMLImageElement;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
    this.image = new Image();
    this.image.src = "cat.png";
  }
  public update(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
  public draw() {
    ctx.drawImage(this.image, this.x, this.y, 50, 50);
  }
}

let cat: Cat;
let mouseX: number;
let mouseY: number;

function init() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  window.addEventListener("resize", () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  });

  canvas.addEventListener("mousemove", (event) => {
    mouseX = event.clientX;
    mouseY = event.clientY;
  });

  cat = new CatImpl(0, 0);
}

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  if (mouseX && mouseY) {
    cat.update(mouseX - 25, mouseY - 25);
  }

  cat.draw();
}

init();
animate();
1269 chars
66 lines

To run the application, you can use a package like parcel-bundler to quickly get a local dev server running by running this command:

index.ts
npx parcel index.html
22 chars
2 lines

Then, navigate to http://localhost:1234/ to see the cat image following your mouse around the screen. Make sure you have the cat.png image in the same directory as your code.

gistlibby LogSnag