Javascript 为什么使用requestAnimationFrame时图像会消失?

Javascript 为什么使用requestAnimationFrame时图像会消失?,javascript,node.js,reactjs,html5-canvas,requestanimationframe,Javascript,Node.js,Reactjs,Html5 Canvas,Requestanimationframe,我画画布并在上面添加一个平面。当我使用setInterval时,画布和平面工作,但如果我使用requestAnimationFrame,平面将消失。平面图像是局部图像,其位置取决于鼠标位置 const canvas = this.refs.canvas const contex = canvas.getContext('2d') function DrawBoard() { contex.fillStyle = "black" contex.fillRect(0, 0, 1200, 3

我画画布并在上面添加一个平面。当我使用setInterval时,画布和平面工作,但如果我使用requestAnimationFrame,平面将消失。平面图像是局部图像,其位置取决于鼠标位置

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

这很可能是因为您在每个循环中重新加载平面图像,并在onload处理程序中绘制它。这将在加载映像后触发异步到平面调用,即使它是从缓存加载的。在此处绘制表示它与渲染循环异步绘制,并且您不控制绘制顺序

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

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"

您在每次平面调用中都要创建图像,我想您可以在声明canvas后创建图像,并使用函数将图像放置在您想要的位置。