Last active
October 23, 2020 19:02
-
-
Save dervondenbergen/deb6b0bd23bce5d616bfb9c0995d1fc0 to your computer and use it in GitHub Desktop.
blur hash as css background, just download as zip and do "npm run start"
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>BlurHash Background</title> | |
</head> | |
<body> | |
<img src="" data-src="https://unsplash.com/photos/Z6blsCKpl1I/download?w=640" data-hash="U47.Hb?@00ogaOx[tQa#4VRRxtRQRjWBafWB" height="959" width="640"> | |
<style> | |
img { | |
background-size: 100% 100%; | |
} | |
</style> | |
<script src="./script.js"></script> | |
</body> | |
</html> |
This file contains hidden or 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
{ | |
"name": "blurhashcssbackground", | |
"version": "1.0.0", | |
"description": "", | |
"main": "script.js", | |
"dependencies": { | |
"@pdf-lib/upng": "^1.0.1", | |
"base64-arraybuffer": "^0.2.0", | |
"blurhash": "^1.1.3" | |
}, | |
"devDependencies": {}, | |
"scripts": { | |
"prestart": "npm install", | |
"start": "npx parcel index.html" | |
}, | |
"author": "Felix De Montis <[email protected]>", | |
"license": "ISC" | |
} |
This file contains hidden or 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
import {decode as decodeBlurhash} from 'blurhash'; | |
import UPNG from '@pdf-lib/upng'; | |
import {encode as encode64} from 'base64-arraybuffer'; | |
function placeholderImage (imageElement) { | |
const height = Math.floor(imageElement.height / 10); | |
const width = Math.floor(imageElement.width / 10); | |
const blurHashString = imageElement.dataset.hash; | |
const pixels = decodeBlurhash(blurHashString, width, height); | |
const png = UPNG.encode([pixels], width, height, 256) ; | |
const data = 'data:image/png;base64,' + encode64(png); | |
return data; | |
} | |
Array.from(document.querySelectorAll('img')).forEach(image => { | |
image.style.backgroundImage = 'url(' + placeholderImage(image) + ')'; | |
var loaderImage = new Image(); | |
loaderImage.onload = () => { | |
image.src = image.dataset.src; | |
} | |
setTimeout(() => { | |
loaderImage.src = image.dataset.src; | |
}, 1000) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment