Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Object based on rotation

I need to center an object in a canvas based on its rotation. I can't figure out the maths.

enter image description here

What information do I have?

  • x, and y coordinates of the top left corner (see red circle of image)
  • width and height of the object
  • the rotation value in degrees

What have i tried so far?

// center horizontally 
if (curretElement === null) return;
curretElement.x((canvas.width() / 2) - ((curretElement.width() * curretElement.scaleX()) / 2));
canvas.draw();

// center vertically
curretElement.y((canvas.height() / 2) - ((curretElement.height() * curretElement.scaleY()) / 2));
canvas.draw();

This centers the image when it's not rotated.

currentElement is the selected object.

canvas is the room where the object should be centered in.

like image 340
David Avatar asked Nov 23 '25 18:11

David


1 Answers

You can calculate the coordinates this way:

  1. imagine that you have your object centered on the canvas
  2. calculate the coordinates of the top left corner relative to the center of the canvas
  3. rotate the object around the center of the canvas and calculate where the top left corner ends up relative to the center of the canvas
  4. translate the relative coordinates of the top left corner back to absolute coordinates

Here is a function that does the calculation:

function calculateXY(canvasWidth, canvasHeight, width, height, angle) {
    //calculate where the top left corner of the object would be relative to center of the canvas
    //if the object had no rotation and was centered
    const x = -width / 2;
    const y = -height / 2;

    //rotate relative x and y coordinates by angle degrees
    const sinA = Math.sin(angle * Math.PI / 180);
    const cosA = Math.cos(angle * Math.PI / 180);
    const xRotated = x * cosA - y * sinA;
    const yRotated = x * sinA + y * cosA;

    //translate relative coordinates back to absolute
    const canvasCenterX = canvasWidth / 2;
    const canvasCenterY = canvasHeight / 2;
    const finalX = xRotated + canvasCenterX;
    const finalY = yRotated + canvasCenterY;

    return { x: finalX, y: finalY };
}
like image 82
mcernak Avatar answered Nov 26 '25 08:11

mcernak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!