【问题标题】:Why does image disappear when using requestAnimationFrame?为什么使用 requestAnimationFrame 时图像会消失?
【发布时间】:2020-05-08 21:30:14
【问题描述】:

我画了canvas 并在上面添加了Plane。当我使用setInterval()canvasPlane 工作,但如果我使用requestAnimationFrame()Plane 就会消失。 Plane 图像是本地的,其位置取决于鼠标位置。

const canvas = this.refs.canvas
const contex = canvas.getContext('2d')

function DrawBoard() {
  contex.fillStyle = "black"
  contex.fillRect(0, 0, 1200, 350)
}

function Plane() {
  const image1 = new Image()
  image1.src = "Plane.png"
  image1.onload = function () {
    contex.drawImage(image1, planeX - 110, planeY - 90, 200, 160);
    }
}

function Game() {
  DrawBoard()
  Plane()
}

function Animate() {
  Game()
  window.requestAnimationFrame(Animate)
}

Animate()

【问题讨论】:

  • 您在每次Plane() 调用时创建图像,我想您可以在声明画布后创建它并使用该函数将图像放置在您想要的位置。

标签: javascript node.js reactjs html5-canvas requestanimationframe


【解决方案1】:

这很可能是由于您在每个循环中重新加载平面图像并将其绘制在onload 处理程序中。一旦图像被加载(即使它是从缓存中加载的),这将触发asyncPlane() 调用。在此处绘制它意味着它正在async 被绘制到您的渲染循环中,并且您无法控制绘制顺序。

相反,您应该在开始渲染之前加载图像并在整个过程中重复使用它。例如:

const canvas = this.refs.canvas
const contex = canvas.getContext('2d')
const image1 = new Image()

function DrawBoard() {
  contex.fillStyle = "black"
  contex.fillRect(0, 0, 1200, 350)
}

function Plane() {
  contex.drawImage(image1, planeX - 110, planeY - 90, 200, 160);
}

function Game() {
  DrawBoard()
  Plane()
}

function Animate() {
  Game()
  window.requestAnimationFrame(Animate)
}

// Start the animation after the plane image is loaded
image1.onload = function () {
  Animate()
}
image1.src = "Plane.png"

【讨论】:

  • 我遇到了同样的问题。如果您有一张图像,上述解决方案可以解决问题。如果你有一堆会发生什么? @smashed-potatoes
猜你喜欢
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 2011-12-21
  • 2015-12-03
相关资源
最近更新 更多