Skip to content

Instantly share code, notes, and snippets.

@Kambfhase
Created June 29, 2011 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kambfhase/1053794 to your computer and use it in GitHub Desktop.
Save Kambfhase/1053794 to your computer and use it in GitHub Desktop.
vection
var vection = (function () {
function vection(){
return vection.create.apply(vection, [].slice.call(arguments));
}
function _extend( target, base) {
for (var key in base) {
if ({}.hasOwnProperty.call(base, key)) {
target[key] = base[key];
}
}
return target;
}
var undefined, _create = Object.create || function (obj) {
function F() {}
F.prototype = obj;
return new F;
};
_extend(vection, {
create: function( left, top) {
var neu = _create( this.prototype);
neu.left = typeof left == "object" ? left.left : (left || 0);
neu.top = typeof left == "object" ? left.top : (top || 0);
return neu;
},
is: function (obj) {
return this.prototype.isPrototypeOf(obj);
},
parse: function( str){
var left = /left:\s*(\d+)/.exec( str),
top= /top:\s*(\d+)/.exec( str);
return vection.create(+(left&&left[1]), +(top&&top[1]));
}
});
_extend(vection.prototype, {
left: 0,
top: 0,
clone: function(){
return vection.create( this);
},
scale: function (lambda) {
var neu = this.clone();
neu.left *= lambda;
neu.top *= lambda;
return neu;
},
add: function( a, b){
var neu = vection.create( a, b);
neu.left += this.left;
neu.top += this.top;
return neu;
},
sub: function( a, b){
return vection.create( a, b).scale(-1).add(this);
},
normalize: function(){
return this.scale(1/this.magnitude());
},
magnitude: function(){
return Math.sqrt( this.left* this.left+ this.top* this.top);
},
manhattan: function(){
return Math.abs( this.left) + Math.abs( this.top);
},
toCSS: function( unit){
return "left: "+this.left+(unit||"px")+"; top:"+this.top+(unit||"px")+" ;";
}
});
return vection;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment