Skip to content

Instantly share code, notes, and snippets.

@bgschiller
Last active September 22, 2017 17:01
Show Gist options
  • Save bgschiller/3f930fb735dcd3d19188f758712c5317 to your computer and use it in GitHub Desktop.
Save bgschiller/3f930fb735dcd3d19188f758712c5317 to your computer and use it in GitHub Desktop.
replace background image when fully loaded.
<style>
body {
width: 100%;
background-repeat: no-repeat;
background-position: 50% 21%;
background-size: cover;
background-image:
/* This larger image will show up on top of the black and white, once it's loaded. */
url(https://s.cdpn.io/23379/[email protected]),
/* Use this low-res, black and white image at first */
url(https://s.cdpn.io/23379/photo-sedona_512x320.jpg);
}
</style>
<style>
body {
width: 100%;
background-repeat: no-repeat;
background-position: 50% 21%;
background-size: cover;
background-image:
/* Use this low-res, black and white image by default */
url(https://s.cdpn.io/23379/photo-sedona_512x320.jpg);
}
</style>
<script>
// compliments to https://stackoverflow.com/a/20285053/1586229
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL('https://s.cdpn.io/23379/[email protected]', function(dataUrl) {
// this callback function will only run when the image is fully loaded.
document.querySelector('body').style.backgroundImage = 'url(' + dataUrl + ')';
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment