1. Problem description

Ios takes a picture and uploads it, and it rotates

Second, the reason why

The iPhone attaches EXIF information (such as lens, aperture, shutter, focal length, camera Angle, etc.) to the photo taken, and automatically rotates the image based on the camera Angle after it is uploaded.

Third, solutions

Solution 1. Add the rotation button, and the user decides which Angle of the picture to use (rotate 90 degrees each time).

Starting:

The process of flipping
1. Modify the width and height of canvas

canvas.width = height;
canvas.height = width;
Copy the code
2. Rotate canvas 90 degrees

⚠️ During rotation, the coordinate axis of canvas will also rotate

ctx.rotate(angle);
Copy the code
3. Move the Canvas to the visual area

ctx.drawImage(img, 0, -height);
Copy the code

Scheme 2. Rotate it back according to the Orientation of the camera in the EXIF information

Pros: No user action, no matter what Angle of the photo, can be rotated back to the downside: developers need to get EXIF information on the image

Three, extension,

1. Rotate 180 degrees

canvas.width = width;
canvas.height = height;
ctx.rotate(angle);
ctx.drawImage(img, -width, -height);
Copy the code

2. Rotate 270 degrees

canvas.width = height;
canvas.height = width;
ctx.rotate(angle);
ctx.drawImage(img, -width, 0);
Copy the code

3. Rotation within 90 degrees (take 30 degrees as an example)

const x = height * Math.sin(angle) * Math.cos(angle);
const y = height * Math.sin(angle) * Math.sin(angle);
canvas.width = height * Math.sin(angle) + width * Math.cos(angle);
canvas.height = height * Math.cos(angle) + width * Math.sin(angle);
ctx.rotate(angle);
ctx.drawImage(img, x, -y);
Copy the code

The code is at 👉