How encode images to webp in browser with vanilla js without plugins

Some days ago, while using a react repo I discovered this method that uses canvas to convert images to webp.

Currently it’s not perfect and in some browsers won’t work on some browsers (guess which one: safari) and has a limited support for icc profiles / color space. You can find more info about project progress here.

HTML Canvas works amazingly fast and without any plugin, it needs only browser while many other method requires NodeJS or PHP GD to work.

the trick is to upload an image to a canvas and then export it with canvas.toDataURL(image/webp, quality).

If you don’t know what webp is I invite you to have a look here, webp provides superior lossless and lossy compression for images on the web (eg. allows a reduction of up to 1000% compared to a transparent png).

So if you haven’t already done so, it’s time to think about how to convert your site images to webp (Modul-r has a gulp task for this purpose).

One last thing… it doesn’t work with avif format, yet at least!

Post navigation

You might be interested in...

No comments yet, be the first!

Comments

Your email address will not be published. Required fields are marked *