Created
June 29, 2011 13:12
-
-
Save Kambfhase/1053794 to your computer and use it in GitHub Desktop.
vection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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