s94-imgclip
Version:
图片裁剪工具
72 lines (71 loc) • 2.69 kB
JavaScript
(function(){
"use strict";
function Vector(x, y, z){
if (arguments.length==1) {
if(x instanceof Vector) return x;
z = x.z;y = x.y;x = x.x;
}
if(!(this instanceof Vector)) return new Vector(x, y, z);
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}
var pro = {
toString: function(){
return "(" + ([this.x, this.y, this.z]).join(", ") + ")";
},
clone: function(){
return new Vector(this.x, this.y, this.z);
},
length: function(){
var hypot = Math.hypot || function(a, b, c){return Math.sqrt(a*a+b*b+c*c); };
return hypot(this.x, this.y, this.z);
},
unit: function(){//当前向量的单位向量
return this.ratio(1/this.length());
},
add: function(v){//向量加 this + v
v = new Vector(v);
return new Vector(this.x+v.x, this.y+v.y, this.z+v.z);
},
subtract: function(v){//向量减 this - v
v = new Vector(v);
return new Vector(this.x-v.x, this.y-v.y, this.z-v.z);
},
ratio: function(n){//标量乘法(数乘)向量的倍数
return new Vector(this.x*n, this.y*n, this.z*n);
},
multiply: function(n){//标量乘法(数乘)倍数
return new Vector(this.x*n, this.y*n, this.z*n);
},
divide: function(n){//标量除法(数除) this / n
return new Vector(this.x/n, this.y/n, this.z/n);
},
dot: function(v){//数量积(点积、内积)向量v在当前向量方向上的投影长度与当前向量长度的乘积
v = new Vector(v);
return this.x*v.x + this.y*v.y + this.z*v.z;
},
cross: function(v){//向量积(叉积、外积)它的几何意义是所得的向量与被乘向量所在平面垂直,方向由右手定则规定,大小是两个被乘向量张成的平行四边形的面积
v = new Vector(v);
return new Vector(this.y*v.z - this.z*v.y, this.z*v.x - this.x*v.z, this.x*v.y - this.y*v.x);
},
//当前向量绕向量v旋转,具象表现为顺着向量v的方向,顺时针转动deg角度
rotate: function(v, deg){
v = new Vector(v);
var vi = v.unit();
//第一步、是对当前向量做正交分解,分解成平行于v的t1和垂直于v的t2两个向量
var t1 = vi.ratio(this.dot(vi));
var t2 = this.subtract(t1);
//第二步、利用外积可以计算与t2和vi都垂直,且长度等于t2的向量t3
var t3 = vi.cross(t2);
//第三步、计算t2旋转deg角度后的向量t4
var t4 = t2.ratio(Math.cos(deg)).add( t3.ratio(Math.sin(deg)) );
//第三步、t4与t1相加得到当前向量旋转后的向量
return t1.add(t4);
},
};
for (var k in pro) {
Object.defineProperty(Vector.prototype, k, {value: pro[k]});
}
module.exports = Vector;
})();