Multiple calls to canvas.putImageData in HTML5

903 Views Asked by At

I'm building an application that makes a user-specified number of calls to canvas.putImageData in Javascript. Between each call to putImageData, the image data is modified. The time needed to modify the data varies between calls. The user also needs to be able to stop the animation while it's running (I'm using a button). Initially I used:

for (var i=0; i < n; i++) {
    canvas.putImageData(imgdata, 0, 0);
    modify(imgdata);
}

However, this doesn't display each frame, only the last one. What does work is to put an alert after canvas.putImageData, but that's super annoying. I tried using setInterval and cancelInterval as I'm sure many would suggest, but this doesn't work for me for two reasons:

  • The time needed to modify the image data varies.
  • setInterval is asynchronous; if the delay I use is too short, calls to modify(imgdata) pile up on the stack and users won't be able to stop the animation when they want.

How can I make this work correctly?

1

There are 1 best solutions below

1
On BEST ANSWER

Use a repeating setTimeout():

var shouldStop = false;

function iteration() {
  canvas.putImageData(imgData, 0, 0);
  modify(imgData);

  if (!shouldStop) {
    window.setTimeout(iteration, 1000);
  }
}

function stop() {
  shouldStop = true;
}

This will display and modify the image data each second.

Another solution would be to delegate the modify algorithm to a web worker.