简体   繁体   English

"在 HTML5 Canvas 和 Javascript 中跟随我的图像移动轨迹"

[英]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.我正在尝试在 HTML5 画布中移动图像,但是当它移动时,它会在其后面创建一条很长的轨迹\/线。 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:您可以像这样使用clearRect<\/a>或自己清空画布:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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