Skip to content

Instantly share code, notes, and snippets.

@DimitarNestorov
Created October 24, 2017 18:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save DimitarNestorov/b5f41b9db33e2059724855009f04a1c9 to your computer and use it in GitHub Desktop.
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