create a canvas animation in typescript

To create a canvas animation in TypeScript, you can utilize the Canvas API provided by HTML5.

First, setup your project by creating an HTML file with a canvas element and a TypeScript file to define your animation.

In your TypeScript file, create a class for your animation that extends the CanvasRenderingContext2D.

index.ts
class Animation extends CanvasRenderingContext2D {
  private x: number;
  private y: number;
  private dx: number;
  private dy: number;
  private radius: number;

  constructor(canvas: HTMLCanvasElement) {
    super(canvas.getContext('2d'));
    this.x = canvas.width / 2;
    this.y = canvas.height / 2;
    this.dx = 2;
    this.dy = 2;
    this.radius = 30;
  }

  draw() {
    this.clearRect(0, 0, canvas.width, canvas.height);
    this.beginPath();
    this.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    this.fillStyle = 'red';
    this.fill();
    this.closePath();
  }

  update() {
    if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
      this.dx = -this.dx;
    }

    if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
      this.dy = -this.dy;
    }

    this.x += this.dx;
    this.y += this.dy;
  }

  animate() {
    requestAnimationFrame(this.animate.bind(this));
    this.draw();
    this.update();
  }
}
982 chars
45 lines

In this example, we have created a simple circle animation that moves around the canvas. We have defined variables for storing the circle's x and y position, as well as its velocity in the x and y directions. We have also defined the radius of the circle.

The draw method uses the Canvas API to draw a circle on the canvas.

The update method updates the circle's position based on its velocity, and checks for collision with the edges of the canvas.

The animate method uses the requestAnimationFrame method to create a loop for updating and drawing the animation.

Finally, in your HTML file, create an instance of your animation and call the animate method to start the animation.

<!DOCTYPE html>
<html>
  <head>
    <title>Canvas Animation</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script type="text/javascript" src="script.js"></script>
  </body>
</html>
200 chars
11 lines
index.ts
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const animation = new Animation(canvas);
animation.animate();
133 chars
4 lines

gistlibby LogSnag