Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Placeholder Generator
const placeholder = (function(){
const cache = {};
const canvas = document.createElement(`canvas`);
const type = (function(){
canvas.width = canvas.height = 100;
const context = canvas.getContext(`2d`);
context.rect(0, 0, 100, 100);
const webp = {
type: `image/webp`,
quality: 1
};
if(canvas.toDataURL(webp.type, webp.quality).startsWith(webp.type, 5)){
return webp;
}
const png = {
type: `image/png`
};
const pngLength = canvas.toDataURL(png.type).length;
const jpeg = {
type: `image/jpeg`,
quality: 0
};
const jpegLength = canvas.toDataURL(jpeg.type, jpeg.quality).length;
return jpegLength < pngLength ? jpeg : png;
}());
return function(width: number, height: number){
const cacheId = `${width}x${height}`;
if(cache[cacheId]) return cache[cacheId];
canvas.width = width;
canvas.height = height;
const placeholder = canvas.toDataURL(type.type, type.quality);
return cache[cacheId] = placeholder;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment