Javascript function that works like actionscript's normalize(1)

自古美人都是妖i 提交于 2020-01-03 15:34:40

问题


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 in Javascript

回答1:


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;
  }
}



回答2:


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};
} 



回答3:


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




回答4:


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;
}


来源:https://stackoverflow.com/questions/3592040/javascript-function-that-works-like-actionscripts-normalize1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!