Skip to content

Instantly share code, notes, and snippets.

@tamask
Created October 4, 2012 16:35
Show Gist options
  • Select an option

  • Save tamask/3834814 to your computer and use it in GitHub Desktop.

Select an option

Save tamask/3834814 to your computer and use it in GitHub Desktop.
Boxfill = function(el) {
this.init(el);
};
Boxfill.prototype = {
init: function(el) {
this.el = el;
this.el.style.overflow = 'hidden';
if (!this.el.style.position)
this.el.style.position = 'relative';
this.inner = document.createElement('div');
this.inner.style.position = 'absolute';
this.inner.style.left = '50%';
this.inner.style.top = '50%';
this.el.appendChild(this.inner);
var children = Array.prototype.slice.call(this.el.childNodes);
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child != this.inner)
this.inner.appendChild(child);
}
var self = this;
var proxy = function() {self.update()};
if (window.attachEvent)
window.attachEvent('onresize', proxy);
else {
window.addEventListener('resize', proxy);
window.addEventListener('orientationchange', proxy);
}
},
update: function() {
var viewport_width = this.el.clientWidth;
var viewport_height = this.el.clientHeight;
var natural_width = parseInt(
this.el.getAttribute('data-natural-width'), 10);
var natural_height = parseInt(
this.el.getAttribute('data-natural-height'), 10);
var scale = Math.max(
viewport_width / natural_width,
viewport_height / natural_height);
var frame_width = natural_width * scale;
var frame_height = natural_height * scale;
this.inner.style.width = frame_width + 'px';
this.inner.style.height = frame_height + 'px';
this.inner.style.marginLeft = -(frame_width / 2) + 'px';
this.inner.style.marginTop = -(frame_height / 2) + 'px';
}
};
function boxfill(el) {
return new Boxfill(el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment