解决html中图片显示角度的问题

项目中遇到上传的照片,展示在网页中的时候角度不对,exif-js可以解决这个问题

html

<!DOCTYPE html>
<html>
<head>
<title>1111</title>
</head>
<body>
<img src="./123.JPG" width="300" class="preivew2">
<script src="https://cdn.jsdelivr.net/npm/exif-js"></script>
</body>
</html>

js

<script type="text/javascript">
rotateImg('./123.JPG').then(
    blob => {document.querySelector('.preivew2').src = URL.createObjectURL(blob)}
)
function rotateImg(file) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.src = file;
        img.onload = () => {
            // 获取图片源数据 上面已经引入EXIF全局变量
            EXIF.getData(img, function () {
                // 获取图片orientation值
                console.log(EXIF.getTag(this, "Orientation"))
                let orientation = EXIF.getTag(this, "Orientation");
                let canvas = document.createElement("canvas");
                let ctx = canvas.getContext("2d");
                console.log(orientation,canvas,ctx)
                switch (orientation) {
                    case 3: // 旋转180°
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.rotate((180 * Math.PI) / 180);
                        ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
                        break;
                    case 8: // 旋转90°
                        canvas.width = img.height;
                        canvas.height = img.width;
                        ctx.rotate((90 * Math.PI) / 180);
                        ctx.drawImage(img, 0, -img.height, img.width, img.height);
                        break;
                    case 6: // 旋转-90°
                        canvas.width = img.height;
                        canvas.height = img.width;
                        ctx.rotate((-90 * Math.PI) / 180);
                        ctx.drawImage(img, -img.width, 0, img.width, img.height);
                        break;
                    default: // 没有源信息的图片和正常的图片是不需要旋转的
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0, img.width, img.height);
                        break;
                }
                
                canvas.toBlob(file => resolve(file), 'image/jpeg', 1)
            })
        }
    })
}
</script>