a cat sprite image that follows your mouse which looks like a ball of yarn in typescript

To achieve this effect, we can use HTML5 canvas element and write TypeScript code that will draw and animate the cat sprite image. The following steps can be followed to implement this effect:

  1. Create an HTML5 canvas element in your HTML file with a unique id:
<canvas id="canvas"></canvas>
30 chars
2 lines
  1. Load the cat sprite image into an Image object and wait for it to load before using it:
index.ts
const catImage = new Image();
catImage.src = "cat.png";
catImage.onload = () => {
  // execute code after image has loaded
};
126 chars
6 lines
  1. Create a TypeScript class for the cat object that will hold its state and provide methods for drawing and updating it:
index.ts
class Cat {
  x: number;
  y: number;
  catImage: HTMLImageElement;

  constructor(x: number, y: number, catImage: HTMLImageElement) {
    this.x = x;
    this.y = y;
    this.catImage = catImage;
  }

  draw(ctx: CanvasRenderingContext2D) {
    ctx.drawImage(this.catImage, this.x, this.y);
  }

  update(mouseX: number, mouseY: number) {
    this.x = mouseX;
    this.y = mouseY;
  }
}
388 chars
21 lines
  1. Instantiate the cat object and initialize it with the cat sprite image:
index.ts
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d")!;

const cat = new Cat(0, 0, catImage);
147 chars
5 lines
  1. Add an event listener to the canvas element that will update the cat's position on mousemove:
index.ts
canvas.addEventListener("mousemove", (e) => {
  cat.update(e.clientX, e.clientY);
});
86 chars
4 lines
  1. Add an animation loop using requestAnimationFrame to draw and animate the cat:
index.ts
function animate() {
  // clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // draw cat
  cat.draw(ctx);

  // request next frame
  requestAnimationFrame(animate);
}

animate();
196 chars
13 lines
  1. Be sure to add styles to position the canvas element and hide the cat sprite image:
canvas {
  position: absolute;
  top: 0;
  left: 0;
}

img {
  display: none;
}
80 chars
10 lines

This should create a canvas element with a cat sprite image that follows your mouse and looks like a ball of yarn.

gistlibby LogSnag