javascriptmathvector

javascript formula for computing the vector normal


The following question was asked and answered:

Given 2 points how do I draw a line at a right angle to the line formed by the two points?

However, I am wanting to use it in a javascript function and would like to know how to complete the step where the vector is normalised :

The unit vector of the normal vector is given by dividing each component by the length of the vector.

I have no experience of vector mathematics, but in order to obtain the 'rno' vector, I have to take the inverse of the vector and multiply it by the left or the right normal - I think. Can anyone help me understand how to achieve this pls? I think I have to multiply all the components, but am at the end of a long day, and math tutorials are all looking like Greek.

Thanks in advance.


Solution

  • Every vector is defined by to values eg. x and y. Length of the vector is given by equation length = sqrt(x^2+y^2). Operation of obtaining unit vertor is called normalization. As you wrote, in order to normalize vector, we divide each vector component by length.

    Here's an example of implementation in JavaScript. First of all, you need to define a vector somehow. We'll create new object called Vector for that. Then we'll add a function that calculates the length and normalizes the x and y values:

    class Vector {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      } 
    
      get length() {
        const { x, y } = this;
        return (x**2 + y**2)  ** 0.5;
      }
        
      normalize() {
        const { length } = this;
        this.x /= length;
        this.y /= length;
        return this;
      }
    }
    
    // create an instance of Vector:
    const v = new Vector(2,4);
    console.log(v);
    
    // normalize it:
    const n =  v.normalize();
    console.log(n);