Skip to content

Instantly share code, notes, and snippets.

@dervondenbergen
Last active October 23, 2020 19:02
Show Gist options
  • Save dervondenbergen/deb6b0bd23bce5d616bfb9c0995d1fc0 to your computer and use it in GitHub Desktop.
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"
<!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>
{
"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 <felix@demont.is>",
"license": "ISC"
}
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