Progressively loaded background-image
by tsucres
HTML
<div class="progressive-bg-image" id="ex1">
<!-- Progressively loads the background -->
<img class="hidden thumbnail"...
CSS
.full-absolute {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
}
.progressive-img-load-canvas {
-webkit-transition: opacity 1s;
transition: opacity 1s;
}
.full-loaded .progressive-img-load-canvas {
opacity: 0;
}
.progressive-bg-image {
background-position: center center;
background-size: cover;
position: relative;
}
.hidden {
display: none;
visibility: hidden;
}
/* ============ */
/* === Data === */
/* ============ */
.center-content {
position: relative;
display: table;
text-align: center;
}
.center-content .center {
display: table-cell;
vertical-align: middle;
}
.sample-background {
height: 300px;
width: 100%;
}
.white {
color: white;
}
JavaScript
function initBgImage(root_el) {
var miniatureImg = root_el.querySelector(".thumbnail");
var canvas = root_el.querySelector(".progressive-img-load-canvas");
drawMiniatureForBgImage(root_el, miniatureImg, canvas);
}
function drawMiniatureForBgImage(root_el, miniatureImg, canvas) {
var thumbnail = new Image();
thumbnail.onload = function () {
offsets = [];
window.getComputedStyle(root_el, null).backgroundPosition.split(" ").forEach(function(offset) {
offsets.push(parseInt(offset) / 100);
});
var canvasImage = new CanvasImage(canvas, thumbnail, canvas.offsetWidth, canvas.offsetHeight, offsets[0], offsets[1]);
canvasImage.blur(2);
};
thumbnail.src = miniatureImg.src;
}
function loadFullBgImage(root_el) {
var fullBgImg = root_el.querySelector(".full-bg-image"),
canvas = root_el.querySelector(".progressive-img-load-canvas");
console.log(canvas);
console.log(fullBgImg);
function fullBackgroundImageLoaded() {
root_el.style.backgroundImage = 'url(' + fullBgImg.src + ')';
window.requestAnimationFrame(function() {
root_el.classList.add("full-loaded");
});
}
if (fullBgImg.src && fullBgImg.complete) {
fullBackgroundImageLoaded();
} else {
fullBgImg.addEventListener('load', fullBackgroundImageLoaded);
fullBgImg.addEventListener('error', console.log);
if (fullBgImg.hasAttribute("data-src")) {
fullBgImg.src = fullBgImg.dataset.src;
}
}
}
// source: pilpil.js
CanvasImage = function (canvasEL, image) {
this.image = image;
this.element = canvasEL;
canvasEL.width = image.width;
canvasEL.height = image.height;
this.context = canvasEL.getContext('2d');
this.context.drawImage(image, 0, 0);
};
CanvasImage.prototype = {
blur:function(e) {
this.context.globalAlpha = 0.5;
for(var t = -e; t <= e; t += 2)...