doughaase
doughaase

Reputation: 245

Resize image and rotate canvas 90 degrees

There's quite a few topics here about rotating images with canvas on js. I read most of them, and couldn't figure out a solution for my problem.

I'm receiving an image (from an upload component) of whatever resolution. I'm resizing it to 1024x768 like:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");

if (img.width >= img.height) {
    canvas.width = 1024;
    canvas.height = 768;
} else {
    canvas.width = 768;
    canvas.height = 1024;
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);   

It works fine.

But on Safari/iOs, when I take a picture and upload, the image has ALWAYS a higher width value than height, so the code above doesn't work.

So I decided to use exif-js to detect the image's orientation. When the Orientation attribute is higher than 4, I need to rotate the image 90 degrees, and swap height and width values.

I tried to rotate the image like this:

canvas.width = 768; // swapping values
canvas.height = 1024;                                       

ctx.translate(canvas.width/2, canvas.height/2);  // translate to center
ctx.rotate(Math.PI/2); // rotate 90 degrees

ctx.drawImage(img, -img.width/2,-img.height/2); // not sure of the dx and dy values here... 

The image is rotated. But it has taken just a small portion of the original image to display on the canvas, so it feels "zoomed in"... it seems that I'm using the wrong values on the drawImage method, but not sure how to fix.

How can I fix this rotation with fixed height and width values?

Upvotes: 2

Views: 3978

Answers (1)

Blindman67
Blindman67

Reputation: 54026

To rotate 90 deg clockwise on a new canvas.

const canvas = document.createElement("canvas");
canvas.width = image.height;
canvas.height = image.width;
const ctx = canvas.getContext("2d");
ctx.setTransform(
     0,1, // x axis down the screen
    -1,0, // y axis across the screen from right to left
    image.height, // x origin is on the right side of the canvas 
    0             // y origin is at the top
);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0); // restore default

If you need to scale the image to fit a size (assuming image will be rotated)

const width = 1024; // after rotation
const height = 768; // after rotation
const scale = width / image.height; // how much to scale the image to fit
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const  ctx = canvas.getContext("2d");
ctx.setTransform(
     0,scale, // x axis down the screen
    -scale,0, // y axis across the screen from right to left
    width,    // x origin is on the right side of the canvas 
    0         // y origin is at the top
);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0); // restore default

Upvotes: 4

Related Questions