chromium/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-placeholder-image-source.html

<!DOCTYPE html>
<title>Test using a placeholder canvas as an image source.</title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>

<script>
var t = async_test("Test that using a placeholder canvas as a source image accesses the image that was committed to the associated OffscreenCanvas.");
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var offscreen = canvas.transferControlToOffscreen();

var ctx = offscreen.getContext('2d');
ctx.fillStyle = '#0f0';
ctx.fillRect(0, 0, 100, 100);
t.step(() => {
  assert_true(verifyImage(canvas, [0, 0, 0, 0]),
              "Verify that OffscreenCanvas.commit() does not propagate the " +
                  "image synchronously to the placeholder canvas.");
});

var kGreen = [0, 255, 0, 255];

function verifyImage(image, expectedColor, description) {
  var testCanvas = document.createElement('canvas');
  var testCtx = testCanvas.getContext('2d');
  testCtx.drawImage(image, 0, 0);

  var pixel = testCtx.getImageData(50, 50, 1, 1).data;
  return pixel.every((c, i) => c === expectedColor[i]);
}

// Returns a Promise that resolves only once the placeholder canvas contents
// have been updated, which may take an arbitrary number of scheduling
// iterations.
function waitForPlaceholderImage() {
  return new Promise(resolve => {
    var tryVerifyPlaceholderImage = function() {
      if (!verifyImage(canvas, kGreen)) {
        setTimeout(tryVerifyPlaceholderImage, 4);
        return;
      }

      resolve();
    };

    setTimeout(tryVerifyPlaceholderImage);
  });
}

waitForPlaceholderImage().then(() => {
  var testImage = new Image;
  testImage.src = canvas.toDataURL();
  testImage.onload = function() {
    t.step(() => {
      assert_true(verifyImage(canvas, kGreen),
                  "verify that toDataURL works on placeholder canvas.");
    });
    canvas.toBlob(blob => {
      createImageBitmap(blob).then(image => {
        t.step(() => {
          assert_true(verifyImage(image, kGreen),
                      "verify that toBlob works on placeholder canvas.");
        });
        t.done();
      })
    });
  }
});
</script>