Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all new coordinates of rotated SVG rectangle using JavaScript

I am trying to find the rotated svg rectangle coordinates.

For example,

<svg width="500" height="500">
  <rect width="100" height="80" x="250" y="50"/>
</svg>

Before rotation

In this SVG rect, i can calculate all 4 corners as mentioned below.

Point-1 => (250,50)

point-2 => (350,50) i.e (x+width, y)

Point-3 => (350, 130) i.e (x+width, y+height)

point-4 => (250, 130)

But, when i use the rotate, i can't find new 4 coordinates,

<svg width="500" height="500">
  <rect width="100" height="80" x="250" y="50"  transform="rotate(10 250,50)"/>  
</svg>

after rotation

like image 374
Santhosh Avatar asked Oct 15 '22 07:10

Santhosh


1 Answers

I found the solution. The below method is working fine.

function degreeToRadian(degree) {
        return degree * (Math.PI / 180);
}
  

    function getRotatedRectangleCoordinates(actualPoints, centerX, centerY, angle) {
        var coordinatesAfterRotation = [];
        for (var i = 0; i < 4; i++) {
            var point = actualPoints[i];
            var tempX = point.x - centerX;
            var tempY = point.y - centerY;
            var rotatedX = tempX * Math.cos(degreeToRadian(angle)) - tempY * Math.sin(degreeToRadian(angle));
            var rotatedY = tempX * Math.sin(degreeToRadian(angle)) + tempY * Math.cos(degreeToRadian(angle));
            point.x = rotatedX + centerX;
            point.y = rotatedY + centerY;
            coordinatesAfterRotation.push({ 'x': point.x, 'y': point.y });
        }
        return coordinatesAfterRotation;
    }
like image 136
Santhosh Avatar answered Oct 31 '22 10:10

Santhosh