Languages
[Edit]
EN

JavaScript - rotate vector 2D to left direction (counterclockwise direction)

8 points
Created by:
trincot
330

In this short article, we would like to show how to rotate any vector 2D to the left side (90 degrees) using Javascript.

Quick solution:

function rotateLeft(vector) {
	return { x: -vector.y, y: vector.x };
}

var vector1 = {x: 2, y: 4};         // vector V1 = [ 2,  4]
var vector2 = rotateLeft(vector1);  // vector V2 = [-4,  2]

Rotation preview:

Vector 2D rotation to the left direction (counterclockwise direction) using JavaScript.
Vector 2D rotation to the left direction (counterclockwise direction) using JavaScript.

Practical example

// ONLINE-RUNNER:browser;

function rotateLeft(vector) {
	return { x: -vector.y, y: vector.x };
}


// Usage example:

                                     // direction:
var vector1 = {x: 0, y: 1};          //   ↑

var vector2 = rotateLeft(vector1);   //   ←
var vector3 = rotateLeft(vector2);   //   ↓
var vector4 = rotateLeft(vector3);   //   →

console.log(vector1.x + ' ' + vector1.y);  //  0  1      ↑
console.log(vector2.x + ' ' + vector2.y);  // -1  0      ←
console.log(vector3.x + ' ' + vector3.y);  //  0 -1      ↓
console.log(vector4.x + ' ' + vector4.y);  //  1  0      →

Note: the above example works on free vectors - typical mathematical vectors that are not localised.

See also

  1. JavaScript - rotate vector 2D to right direction (clockwise direction)
  2. JavaScript - rotate localized vector 2D to right direction (clockwise direction)

  3. JavaScript - rotate localized vector 2D to left direction (counterclockwise direction)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join