OffscreenCanvas: getElementImageDefaultSize() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Want more browser support for this feature? Tell us why.

The getElementImageDefaultSize() method of the OffscreenCanvas interface returns an object containing the default size, in canvas units, of an ElementImage when drawn with drawElementImage() (specifying no destination size).

Syntax

js
getElementImageDefaultSize(element)

Parameters

element

A reference to an ElementImage.

Return value

An object containing the following properties:

height

The default height of the element image, in canvas units.

width

The default width of the element image, in canvas units.

Note: These are live values that will change if, for example, the canvas resolution changes.

Exceptions

InvalidStateError DOMException

Thrown if the element has not yet been painted, meaning there is currently no rendered state to capture the size of.

Examples

Returning the default size of an element image

Our Canvas 2D context offscreen canvas example (source code) shows how to render an element on an offscreen canvas using drawElementImage(). Below, we walk through the pertinent part that features getElementImageDefaultSize(); see drawElementImage() for a full example walkthrough.

In our worker script's message event handler, if data contains an ElementImage of our <form>, we render it to the <canvas>. We start by getting references to the ElementImage and the OffscreenCanvas, then fill the entire canvas context with a solid color using the fillStyle property and fillRect() method.

We then draw the form to the canvas using drawElementImage(). Because we included preserveElementGeometry: true, we need to call updateElementGeometry() to update the element geometry so that it will be interactive as expected. Finally, we log the element's original size to the console, retrieved using getElementImageDefaultSize(), and call ElementImage.close() to free up the memory used to store the element image now we no longer need it:

js
  if (data.formImage) {
    const img = data.formImage;
    const offscreen = ctx.canvas;

    ctx.fillStyle = "#7D82B8";
    ctx.fillRect(0, 0, offscreen.width, offscreen.height);

    ctx.drawElementImage(img, x, y, {
      preserveElementGeometry: true,
    });

    offscreen.updateElementGeometry(img, {
      canvasTransform: new DOMMatrix().translate(x, y),
    });

    console.log(offscreen.getElementImageDefaultSize(img));

    img.close();
  }
});

The getElementImageDefaultSize() method returns an object along the following lines:

js
{
  "height": 149,
  "width": 230.125
}

Specifications

This feature does not appear to be defined in any specification.

Browser compatibility

See also