简体   繁体   中英

Why does image disappear when using requestAnimationFrame?

I draw canvas and add a Plane on it. The canvas and Plane work when I use setInterval() , but if I use requestAnimationFrame() , the Plane disappears. The Plane image is local and its position depends on the mouse position.

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

This is most likely due to the fact that you re-loading the plane image every loop and drawing it in the onload handler. This will fire async to the Plane() call once the image is loaded (even if it is loaded from cache). Drawing it here means it is being drawn async to your render loop and you aren't controlling your draw order.

Instead, you should load the image prior to starting your rendering and re-use it throughout. Eg:

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"

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