【问题标题】:Moving trail after my image in HTML5 Canvas & Javascript在 HTML5 Canvas 和 Javascript 中跟随我的图像移动火车
【发布时间】:2022-02-06 20:12:27
【问题描述】:

我正在尝试在 HTML5 画布中移动图像,但是当它移动时,它会在其后面创建一条很长的轨迹/线。我不确定如何在不出现长尾线的情况下移动图像。任何帮助将不胜感激

//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()

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    您必须在更新绘制调用之间清除画布,否则弹丸会被一遍又一遍地绘制。您可以使用clearRect 或自行清空画布,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2013-06-03
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2012-01-02
      相关资源
      最近更新 更多