Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
frosted glass effect
<script src="//cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="//rawgit.com/abduzeedo/ios7-blur-html5/master/js/StackBlur.js"></script>
var getElementOffset = function (element) {
var de = document.documentElement;
var box = element.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
};
var applyGlass = function (backgroundElement) {
backgroundElement = backgroundElement || document.getElementsByClassName('defaultbg')[0];
var blur = 8;
var glassParents = document.getElementsByClassName('glass');
for (var i = 0; i < glassParents.length; i++) {
var glassParent = glassParents[i];
var glassCanvas = glassParent.glassCanvas;
if (!glassCanvas) {
glassCanvas = document.createElement('canvas');
glassCanvas.classList.add('glassCanvas');
glassCanvas.style.position = 'absolute';
// glassCanvas.style.filter = 'blur(' + blur + 'px)';
// glassCanvas.style.top = (0 - blur + glassParent.style.marginTop) + 'px';
// glassCanvas.style.left = (0 - blur + glassParent.style.marginLeft) + 'px';
glassCanvas.style.width = (glassParent.clientWidth + blur) + 'px';
glassCanvas.style.height = (glassParent.clientHeight + blur) + 'px';
glassCanvas.id = (Math.random() * 999999).toString();
glassCanvas.width = glassParent.clientWidth + blur;
glassCanvas.height = glassParent.clientHeight + blur;
var firstChild = glassParent.childNodes[0]; //TODO: make this work without child nodes too.
glassParent.insertBefore(glassCanvas, firstChild);
glassParent.glassCanvas = glassCanvas;
}
html2canvas(backgroundElement, {
useCORS: true,
glassCanvas: glassCanvas,
onrendered: function (backgroundScreenshot) {
var glassCanvasContext = this.glassCanvas.getContext('2d');
glassCanvasContext.fillStyle = "#fff";
glassCanvasContext.fillRect(0, 0, this.glassCanvas.clientWidth, this.glassCanvas.clientHeight );
glassCanvasContext.globalAlpha = 0.8;
var pos = getElementOffset(this.glassCanvas);
glassCanvasContext.drawImage(backgroundScreenshot,
pos.left, pos.top, this.glassCanvas.clientWidth, this.glassCanvas.clientHeight, //source
0, 0, this.glassCanvas.clientWidth, this.glassCanvas.clientHeight //dest
);
stackBlurCanvasRGB(
this.glassCanvas.id,
0,
0,
this.glassCanvas.clientWidth, this.glassCanvas.clientHeight,
blur);
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment