Javascript function that works like actionscript's normalize(1)
I need a formula that returns normalize numbers for xy point - similar to actionscript's normalize() function.
var normal = {x:pt1.x-pt2.x,y:pt1.y-pt2.y};
normal = Normalize(1) // this I do not know how to implement i开发者_JS百科n Javascript
I think the as3 normalize function is just a way to scale a unit vector:
function normalize(point, scale) {
var norm = Math.sqrt(point.x * point.x + point.y * point.y);
if (norm != 0) { // as3 return 0,0 for a point of zero length
point.x = scale * point.x / norm;
point.y = scale * point.y / norm;
}
}
This is how it could be written in Actionscript:
function normalize(p:Point,len:Number):Point {
if((p.x == 0 && p.y == 0) || len == 0) {
return new Point(0,0);
}
var angle:Number = Math.atan2(p.y,p.x);
var nx:Number = Math.cos(angle) * len;
var ny:Number = Math.sin(angle) * len;
return new Point(nx,ny);
}
So, I guess in JS it could be something like this:
function normalize(p,len) {
if((p.x == 0 && p.y == 0) || len == 0) {
return {x:0, y:0};
}
var angle = Math.atan2(p.y,p.x);
var nx = Math.cos(angle) * len;
var ny = Math.sin(angle) * len;
return {x:nx, y:ny};
}
I also found this that seems to do it.
var len = Math.sqrt(normal.x * normal.x + normal.y * normal.y)
normal.x /= len;
normal.y /= len;
THANK YOU
Port from the AS3 Point Class, parameter is the same as shown in the livedocs (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/Point.html#normalize() )
Point.prototype.normalize = function(thickness){
var norm = Math.sqrt(this.x * this.x + this.y * this.y);
this.x = this.x / norm * thickness;
this.y = this.y / norm * thickness;
}
精彩评论