Created
October 24, 2017 18:55
-
-
Save DimitarNestorov/b5f41b9db33e2059724855009f04a1c9 to your computer and use it in GitHub Desktop.
Placeholder Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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