Google Chrome and MS Edge > 18 can create a WebP Blob representing the image contained in a canvas:
canvas.toBlob(callback, 'image/webp', 0.8);
This polyfill adds the ability to do the same on browsers that do not support this natively (Firefox, Safari, MS Edge <= 18 and others). It creates a WebP blob from the canvas' pixel data, through a web worker. The web worker calls a WebAssembly WebP encoder to make a WebP blob. The WebP encoder used is: https://github.com/saschazar21/webassembly/tree/master/packages/webp
Copy the files in the dist
directory in your document root.
Include dist/toblob-webp-polyfill.js
in your page:
<script src="/path/to/dist/toblob-webp-polyfill.js"></script>
That's it!
Simply call canvas.toBlob
with the image/webp
mimetype, and an optional quality
argument:
const canvas = document.querySelector('canvas');
const img = new Image();
canvas.toBlob(function(blob) {
const url = window.URL || window.webkitURL;
img.src = url.createObjectURL(blob);
}, 'image/webp', 0.8);
There are some configuration parameters in file toblob-webp-polyfill.js
.
You can set useAlpha
(boolean) to false to disable support for alpha channels.
The webpOptions
object allows for tuning the options for the WebP encoder.
More info on the available options can be found on the web:
- Firefox and Safari: this polyfill enables saving the image on a canvas as a WebP image.
- Chrome: saving the image on a canvas as WebP image is supported natively: this polyfill remains dormant
- MS Edge > 18: saving the image on a canvas as WebP image is supported natively: this polyfill remains dormant
- MS Edge <= 18: This browser doesn't have
canvas.toBlob
. This polyfill provides an alternativecanvas.toBlob
implementation and allows you to save a canvas asimage/webp
. - Internet Explorer: Not supported (on all versions)
This Polyfill is used (among others) on the following websites:
This plugin is released under the MIT license. It is simple and easy to understand and places almost no restrictions on what you can do with the code. More Information
The development of this plugin was funded by Zygomatic.