nvgif.js - NVGIF JavaScript implementation¶
Source: nvgif.js
The JavaScript implementation of NVGIF uses pako via jsDelivr.
It uses a MutationObserver to look for changes in the DOM.
When it detects one, it sweeps through all undecoded NVGIFs in the page and decodes them.
It supports <img> and <picture> elements.
It supports all versions (decode‑only).
- async globalThis.loadNVGIF(src)¶
Decodes the NVGIF at the URL
srcand returns the image data in the form of an OffscreenCanvas.
- class globalThis.NVGIFImage(src)¶
This class tries to mimic the behavior of
Image. When it is created, it starts loading the image atsrc.If the load succeeds, calls
onloadwith no arguments and setsimgDatato anImageDataobject with the decoded data.If the load fails, calls
onerrorwith no arguments.
- globalThis.NVGIFImage.onload¶
A callback called upon a successful load.
- globalThis.NVGIFImage.onerror¶
A callback called upon a failed load.
- globalThis.NVGIFImage.imgData¶
If the load was successful, contains an ImageData object with decoded image data, otherwise
null.
- globalThis.NVGIFImage.canvas¶
If the load was successful, contains an OffscreenCanvas object with decoded image data on its surface, otherwise
null.
Example
Show an NVGIF via the image element:
<img src="images/drawing.nvg">
<script type="module" src="nvgif.js"></script> <!-- nvgif.js -->
Draw an image onto a canvas:
<canvas id="myCanvas" width="400" height="400" style="border:1px solid grey"></canvas>
<script type="module" src="nvgif.js"></script> <!-- nvgif.js -->
<script>
window.addEventListener("DOMContentLoaded", () => { // important!!
(async() => {
const imgCanvas = await loadNVGIF("images/drawing.nvg");
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.drawImage(imgCanvas, 40, 40);
})();
});
</script>