radio/lorgar/views/image.js

105 lines
3.8 KiB
JavaScript

"use strict";
(function() {
var moduleName = "views/image";
var deps = [];
deps.push("views/view");
define(moduleName, deps, function() {
var View = require("views/view");
var Image = View.inherit({
className: "Image",
constructor: function(controller, options) {
var base = {
preserveAspectRatio: false,
aspectRatio: 1 // width / height
};
W.extend(base, options)
if (base.preserveAspectRatio) {
base.sizeDependency = View.SizeDependency.straight.straight;
if (base.maxWidth || base.maxHeight) {
var max = closestSize(base.maxWidth || Infinity, base.maxHeight || Infinity, base.aspectRatio); //TODO really not sure about that
base.maxWidth = max.w;
base.maxHeight = max.h;
}
if (base.minWidth || base.minHeight) {
var min = closestSize(base.minWidth || 0, base.minHeight || 0, base.aspectRatio);
base.minWidth = min.w;
base.minHeight = min.h;
}
}
var el = document.createElement("img");
View.fn.constructor.call(this, controller, base, el);
controller.needData();
},
destructor: function() {
this._f.dontNeedData();
View.fn.destructor.call(this);
},
_onData: function() {
if (this._f.hasData()) {
this._e.src = "data:" + this._f.getMimeType() + ";base64," + this._f.data.base64(); //TODO figure out if that could be done with URLObject
}
},
_closestSize: function(w, h) {
if (this._o.preserveAspectRatio) {
return closestSize(w, h, this._o.aspectRatio);
} else {
return View.fn._closestSize.call(this, w, h);
}
},
"getMinWidthForHeight": function(h) {
if (this._o.preserveAspectRatio) {
return this.constrainWidth(h * this._o.aspectRatio);
} else {
return this._o.minWidth;
}
},
"getMaxWidthForHeight": function(h) {
if (this._o.preserveAspectRatio) {
return this.constrainWidth(h * this._o.aspectRatio);
} else {
return this._o.maxWidth;
}
},
"getMinHeightForWidth": function(w) {
if (this._o.preserveAspectRatio) {
return this.constrainHeight(w / this._o.aspectRatio);
} else {
return this._o.minHeight;
}
},
"getMaxHeightForWidth": function(w) {
if (this._o.preserveAspectRatio) {
return this.constrainHeight(w / this._o.aspectRatio);
} else {
return this._o.maxHeight;
}
}
});
function closestSize(w, h, ratio) {
var nh = w / ratio;
var nw = h * ratio;
var dh = Math.abs(h - nh);
var dw = Math.abs(w - nw);
if (dh > dw) {
return {
w: nw,
h: h
}
} else {
return {
w: w,
h: nh
}
}
}
return Image;
})
})();