0

I'm trying to copy image contents into a canvas, pixel by pixel and I want that to be visualized while it's happening. However, the canvas just stays blank while the process is undergoing and then when it's finished, the cloned image is displayed in full. Is there any way for the canvas to be "refreshed" or "reloaded" after every pixel change?

Here is part of the code I'm using:

for (var x = 0; x < w; x++) {
    for (var y = 0; y < h; y++) {
        ctx2.putImageData(ctx1.getImageData(x,y,1,1),x,y);
    }
}

...where ctx1 is the context object of the original and ctx2 - context object of the clone. I'm interested in this only for visualization purposes. I'm aware it's probably not quite efficient.

Amati
  • 1,484
  • 1
  • 16
  • 29
  • 1
    You could use a generator function as described [here](http://stackoverflow.com/a/40741857/6854845) – Jon Nov 24 '16 at 18:52

1 Answers1

1

I managed to do it eventually by using the setIntervalX function described here, with 1 millisecond delay. Draws line by line, instead of pixel by pixel but it's good enough for me and likely more efficient. Code would probably be neater with the generator function Jon suggested in the comments above but I've battled this long enough already and I just need something that works :)

var x = 0;
setIntervalX(function(){drawVerticalLine(ctx1,ctx2,x++,image_height)},1,image_width);

function setIntervalX(callback, delay, repetitions) {
    var r = 0;
    var intervalID = window.setInterval(function () {

       callback();

       if (++r === repetitions) {
           window.clearInterval(intervalID);
       }
    }, delay);
}

function drawVerticalLine(ctx1,ctx2,x,image_height) {
    for (var y = 0; y < image_height; y++) {
        ctx2.putImageData(ctx1.getImageData(x,y,1,1),x,y);
    }
}
Community
  • 1
  • 1
Amati
  • 1,484
  • 1
  • 16
  • 29