Created
March 18, 2021 21:13
-
-
Save mikeymop/3da0ca5c3024f26d8cac140d4c896061 to your computer and use it in GitHub Desktop.
Compensate-rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Performs coordinate rotation math in order to abstract away positional discrepancies resulting from a | |
* rotated page. | |
* See: https://www.khanacademy.org/computing/pixar/sets/rotation/v/sets-8 | |
* @param {PDFPage} page - The page that may be rotated | |
* @param {number} x - The desired *relative* x-coordinate of the object | |
* @param {number} y - The desired *relative* y-coordinate of the object | |
*/ | |
public compensateRotation(page, x, y): {newX: number, newY: number} { | |
var dimensions = page.getSize(); | |
var rotation = page.getRotation().angle; | |
var rotationRads = rotation * Math.PI / 180; // convert to radians | |
var coordsFromBottomLeft = { x, y }; | |
if(rotation !== 0) { | |
console.log(`Compensating coordinates rotated: ${page.getRotation().angle}`); | |
} | |
console.log(page.getSize()); | |
var newX = null; | |
var newY = null; | |
if(rotation === 90) { // x' = x cosθ - ysinθ; y' = xsinθ + ycosθ | |
// we flip y and x here in the theorem to accomodate for 90 degrees being in portrait orientation | |
newX = coordsFromBottomLeft.y * Math.cos(rotationRads) - coordsFromBottomLeft.x * Math.sin(rotationRads) + dimensions.width; | |
newY = coordsFromBottomLeft.y * Math.sin(rotationRads) + coordsFromBottomLeft.x * Math.cos(rotationRads); | |
} | |
else if(rotation === 180) { // x' = x cosθ - ysinθ; y' = xsinθ + ycosθ | |
newX = coordsFromBottomLeft.x * Math.cos(rotationRads) - coordsFromBottomLeft.y * Math.sin(rotationRads) + dimensions.width; | |
newY = coordsFromBottomLeft.x * Math.sin(rotationRads) + coordsFromBottomLeft.y * Math.cos(rotationRads) + dimensions.height; | |
} | |
else if(rotation === 270) { // x' = x cosθ - ysinθ; y' = xsinθ + ycosθ | |
// we flip y and x to accomodate for 270 being in portrait | |
newX = coordsFromBottomLeft.y * Math.cos(rotationRads) - coordsFromBottomLeft.x * Math.sin(rotationRads) + dimensions.height; | |
newY = Math.abs(coordsFromBottomLeft.y * Math.sin(rotationRads) + coordsFromBottomLeft.x * Math.cos(rotationRads) + dimensions.height) | |
} | |
else { | |
newX = coordsFromBottomLeft.x; | |
newY = coordsFromBottomLeft.y; | |
} | |
console.log(`compensateRotation: x: ${x} y:${y} -> x: ${newX}, y: ${newY}`); | |
return {newX, newY}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment