Search code examples
javascriptimageloopscanvasdelay

How to delay a for loop and run canvas operation?


I would like to be run an iteration of a loop every x seconds.

Every iteration will change the value of a pixel and paint the changed image to the canvas.

So far I have this:

        for(let i=0;i<width;i++){ //Rows
          for(o=i*(width*4);o<i*(width*4)+(width*4);o+=4){//pixels in current row
                imgData.data[o] = 255
          }
          ctx.putImageData(imgData, xPos, yPos);
        }

Which successfully changes all pixels in the image to be 255 red. However, this happens all at the same time. I would like this to happen a pixel a time every x seconds.

Any guidance?


Solution

  • If you want this to happen a pixel every second you shouldn't use the outer for-loop at all. Instead use a global variable which holds the position of the current pixel. With each interval increment that variable and put the changed imageData to the canvas.

    Something like:

    var originalWidth = width;
    var currentPixel = 0;
    
    function update() {
      for (o = currentPixel * (originalWidth * 4); o < currentPixel * (originalWidth * 4) + (originalWidth * 4); o += 4) {
        imgData.data[o] = 255;
      }
      ctx.putImageData(imgData, xPos, yPos);
      if (currentPixel + 1 < originalWidth) {
        currentPixel++
      } else {
        clearInterval(intervalId);
      }
    }
    var intervalId = setInterval(update, 1000);