Home > database >  Animate Circle Javascript Canvas
Animate Circle Javascript Canvas

Time:12-31

I am trying to animate a moving circle from one location to another. In the example below, it is from (10, 10) to (50, 50) Below is the code for my Bullet class. When the user clicks space, I create a new Bullet object and I am trying to animate it. How do I create a smooth animation?

class Bullet{
    
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.size = 10;
    }

    draw(){
        ctx.fillStyle = "green";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
        ctx.fill();
    }
    fire(locationX, locationY){
        
    }
}

document.addEventListener('keydown', function(e){
        if(e.key == ' '){
            var currBullet = new Bullet(10, 10);
            currBullet.fire(50, 50);
        }
});

function reset(){
    ctx.clearRect(0, 0, w, h);
}

CodePudding user response:

You can use requestAnimationFrame to animate the bullets. What is the overall goal of this? Are you planning on shooting bullets from (10, 10) to (50, 50)? Does the distance traveled need to be limited? Or will be be shooting it in a direction based on where the player is facing? Do you want to limit the number of bullets?

This code does what you asked but is very limited.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;

let bullets = [];

class Bullet{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.size = 10;
    }

    draw(){
        ctx.fillStyle = "green";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
        ctx.fill();
    }
    update(){
        this.x  = 1
        this.y  = 1
    }
}

document.addEventListener('keydown', function(e){
        if(e.code === 'Space'){
            fire()      
        }
});

function fire() {
    bullets.push(new Bullet(10, 10))
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (let i=0; i < bullets.length; i  ) {
    bullets[i].draw()
    bullets[i].update()
    if (bullets[i].x >= 50 && bullets[i].y >= 50) {
      bullets.splice(i, 1)
    }
  }
  
  requestAnimationFrame(animate)
}
animate()
<canvas id='canvas'></canvas>

  • Related