Blur background using canvas
Demo using html2canvas and stackblur
by LimitedWard
HTML
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<div class="red"></div>
<h1>Some text that snakes around and down, where will it all end... Can I have my coffee please?</h1>
CSS
body {
margin:0;
padding:0;
}
.red {
padding:40px;
background-color:#e00;
width:0px;
float:right;
}
h1 {
font-family:sans-serif;
line-height:40px
}
canvas {
position:absolute;
top:0;
}
JavaScript
var ww = window.innerWidth;
setIntervalgetBlurredBG(0, 0, ww, 80, 'demo');
function getBlurredBG(x, y, w, h, id) {
html2canvas(document.body, {
onrendered: function (canvas) {
process(canvas, x, y, w, h, id);
},
width: (x + w),
height: (y + h)
});
}
function process(canvas, x, y, w, h, id) {
//create new canvas to enable clipping
var ocanvas = document.createElement('canvas');
ocanvas.width = w;
ocanvas.height = h;
ocanvas.style.left = x + 'px';
ocanvas.style.top = y + 'px';
ocanvas.id = id;
var ctx = ocanvas.getContext('2d');
ctx.drawImage(canvas, x, y, w, h,
0, 0, w, h);
stackBlurCanvasRGB(ocanvas, x, y, w, h, 24)
lighten(ocanvas);
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.fillRect(x, y, w, h);
ctx.fillStyle = '#999';
ctx.font = '32px arial';
ctx.fillText("Partial overlay content", 10, 60);
document.body.appendChild(ocanvas);
}
function lighten(canvas) {
var ctx = canvas.getContext('2d');
var idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = idata.data;
var len = data.length;
var r,g,b;
for (var i = 0; i < len; i += 4) {
r = data[i];
g = data[i+1];
b = data[i+2];
data[i] = r + r * (r / 255) * 0.1;
data[i + 1] = g + g * (g / 255) * 0.1;
data[i + 2] = b + b * (b / 255) * 0.1;
}
ctx.putImageData(idata, 0, 0);
}
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: [email protected]
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
[email protected]
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
Copyright (c) 2010 Mario...