1

I need to save a canvas element as a png image for automated tests. The problem is that data is placed in webgl context so solution like How to save a canvas as PNG in Selenium? doesn't work for me (blank image is returned).

I looked trough some questions (i.e. HTML Save WebGL Canvas as Image) and understood that webgl context data is available only before rendering or preserveDrawingBuffer: true is required. But I'm testing this game and can't modify it.

I may have missed how I can save WebGL canvas as PNG. I would appreciate any advice.

P.S. Taking page screenshot is not solution for me because it takes too much time (up to 10 seconds for some old mobile devices).

UPD1:

@LJᛃ I tried Canvas toDataURL() returns blank image in console:

# find my canvas element
canvas = document.querySelector("canvas")

# run 2 commands from question above
canvas.getContext('webgl', {preserveDrawingBuffer: true});

HTMLCanvasElement.prototype.getContext = function(origFn) {
  return function(type, attributes) {
    if (type === 'webgl') {
      attributes = Object.assign({}, attributes, {
        preserveDrawingBuffer: true,
      });
    }
    return origFn.call(this, type, attributes);
  };
}(HTMLCanvasElement.prototype.getContext);

# trying to get data, but it returns blank image
canvas.toDataURL('image/png').substring(21);

But it still return blank image. Am I doing something wrong?

  • How about overriding `HTMLCanvasElement.prototype.getContext` with a version that always sets `preserveDrawingBuffer` to `true` ? – LJᛃ Jul 02 '21 at 19:05
  • @LJᛃ Could you please explain what do you mean? I've just updated question with the option I tried – Aliaksandr Plekhau Jul 02 '21 at 20:21
  • You have to override `getContext` before the application uses it so basically as soon as possible. – LJᛃ Jul 03 '21 at 10:04
  • @LJᛃ I've already tried it as I showed in question (ran this code in browser console) and it didn't work for me. Is this what you suggest? – Aliaksandr Plekhau Jul 04 '21 at 05:22

0 Answers0