Displayed on the screen is an image element that undergoes a css transform: rotate(degree), with degree ranging from 0 to 360. This transformation makes the image appear rotated, even though its original orientation remains unchanged.
Given this scenario, users can choose an area on the ROTATED image, and the resulting output will detail the selected crop region in relation to the transformed image, not the initial one.
The output will include:
- nativeImageWidth
- nativeImageHeight
- positionX
- positionY
- width
- height
- angle (defaulted to 0 if no previous rotation existed before cropping)
To proceed, a rectangle highlight must be drawn over the user-selected region and then update the displayed image with the modified src data showcasing the highlighted area.
A translation formula is required to convert the cropped area's coordinates into dimensions compatible with the original un-rotated image. These translated values can subsequently be utilized for fillRect operations followed by resetting the img using context.toDataURL
An illustrative example can be viewed at this link: Picture explanation
I have conducted research but couldn't find a solution that matches my specific requirements. The approaches I came across commonly involved using context.rotate() and context.translate(), which weren't effective in my case either.
In essence, I am seeking a solution akin to the following:
function getTranslatedRect(x, y, w, h, angle, nativeImageWidth, nativeImageHeight) {
let newX = x;
let newY = y;
let newWidth = w;
let newHeight = h;
let newCanvasWidth = nativeImageWidth;
let newCanvasHeight = nativeImageHeight;
// perform necessary math calculations beyond my expertise...
newX = 35;
newY = 320;
newWidth = 65;
newHeight = 120;
return {
newX, newY, newWidth, newHeight, newCanvasWidth, newCanvasHeight
};
}
let img = document.getElementById('translatedImage');
let translatedRect = getTranslatedRect(60, 35, 120, 65, 90, 350, 500);
let canvas = document.createElement('canvas');
canvas.width = translatedRect.newCanvasWidth;
canvas.height = translatedRect.newCanvasHeight;
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(255, 165, 0, 1)';
ctx.fillRect(translatedRect.newX, translatedRect.newY, translatedRect.newWidth, translatedRect.newHeight);
img.src = canvas.toDataURL('image/jpg', 1.0);
.canvas {
width: 500px;
height: 500px;
text-align: center;
}
.rotated {
transform: rotate(90deg);
}
translated image with "user highlighted area"
<div class="canvas">
<img id="translatedImage" class="rotated" src="https://i.ibb.co/fNDs6qQ/Untitled.png" crossorigin="anonymous">
</div>
original image
<div class="canvas">
<img id="originalImage" src="https://i.ibb.co/fNDs6qQ/Untitled.png" crossorigin="anonymous">
</div>