简体   繁体   中英

Moving trail after my image in HTML5 Canvas & Javascript

I am trying to move an image in HTML5 canvas but when it moves it creates a long trail\/line behind it. I'm not sure how to have just the image move without a long trail line appearing. Any help would be greatly appreciated

//Create bullets
class Projectile {
  constructor({position, velocity}){
    this.position = position
    this.velocity = velocity
    this.width = 5
    this.height = 10
    this.color = "red";
  }

  draw() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
  }

  update() {
    this.draw()
    this.position.x += this.velocity.x
    this.position.y += this.velocity.y
  }
}

const projectiles = [new Projectile({
  position: {
    x: 300,
    y: 300
  },
  velocity: {
    x: 0,
    y: 0
  }
})]

function animate() {
  projectiles.forEach(projectile => {
    projectile.update()
  })
}

animate()

You have to clear the canvas between the update draw calls, otherwise the projectiles get drawn over and over again. You can use clearRect<\/a> or empty the canvas on your own like this:

ctx.fillStyle = 'black'; //try out 'rgba(0,0,0,0.9)'
ctx.fillRect(0,0,canvas.width,canvas.height);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM