1

I hope you can helpme, I am having a problem rendering a sequence of image movements on canvas. I explain:

I have a function that what it does is slowly move an image (dinosaur) from top to bottom. The function is this:

function dibujarDinosaurio(x) {
  for (let y = 100, j = 0; y <= 500; y++, j++) {
    setTimeout(() => {
      dibujarFondo2()
      papel.drawImage(dinosaurios[x].imagen, 100, y)
    }, j * 10);
  }
}

I have several images that I want to represent in sequence, that is, when the for cycle ends and the first image has been moved to the end, continue with the next image.

I tried to enclose the quoted for loop inside another for loop that distributes one image for each loop. But what happened is that there was only one loop, where the images changed rapidly while the loop occurred.

I thought then that it would be an asynchronous problem due to setTimeOut, so I used async await and it went like this:

const dibujarDinosaurio = x => {
  return new Promise((resolve, reject) => {
    if (true) {
      resolve(dinosaurios[x].imagen)
    }
    else {
      reject(new Error('Error'))
    }
  })
}

const dibujosDinosaurios = async (x) => {
  try {
    const data1 = await dibujarDinosaurio(x)
    const data2 = await dibujarDinosaurio(x + 1)
    for (let y = 100, j = 0; y <= 500; y++, j++) {
      setTimeout(() => {
        dibujarFondo2()
        papel.drawImage(data1, 100, y)
      }, j * 10);
    }
    for (let y = 100, j = 0; y <= 500; y++, j++) {
      setTimeout(() => {
        dibujarFondo2()
        papel.drawImage(data2, 100, y)
      }, j * 10);
    }

  } catch (error) {
    console.error(error)
  }
}

However when executing the code the same thing continues to happen. The 2 images are quickly interchanged until it reaches the end point, where everything stops.

Why is this happening? how do I solve it?

Thanks!!

DJG
  • 29
  • 4

0 Answers0