D
D
DarthJS2015-07-04 23:45:51
JavaScript
DarthJS, 2015-07-04 23:45:51

What is the correct way to use canvas requestAnimationFrame in this situation?

Hello! I am new to JS and learning Canvas. Here I encountered a misunderstanding of the work of drawing images drawImage () together with requestAnimationFrame. Please advise how to proceed in this situation.
For experiments I try to move pictures.
The problem is that the pictures are not displayed, they do not have time to go deep, because when drawing a simple square, everything works.
When init() is called, they are not displayed, but when update is called, everything works. How to fix this situation specifically for this code (I specify what it is for this case, since I understand the elementary work of drawing a picture)? And who can explain why the code works on JSfiddle, but not in the browser?

function init(){
    object.x = 0;
    object.y = 0;
    object.draw();
    loadImage(imgArray);
    for(var i = 0; i < IMG.length; i+=1){
      object.x += 10 * i;
      object.drawImage(IMG[i]);
    };
  };
  function update(){
    ctx.clearRect(0,0,canvas.width, canvas.height);
    object.x +=1;
    object.y +=1;
    object.draw();
    for(var i = 0; i < IMG.length; i+=1){
      object.x +=  i;
      object.drawImage(IMG[i]);
    };

      window.requestAnimationFrame(update);

  };

The complete code can be seen below.
Example on JSfiddle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vasIvas, 2015-07-05
@vasIvas

I did not quite understand what the problem is, but if the pictures do not have time to load, then you need to subscribe to the end of the download. The event is called 'load'. Then you need to wait until all the pictures are loaded and then continue to execute the code further. That is, it is normal if you first download the pictures and only then launch the application.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question