html使用js旋转图片

55次阅读
没有评论

有时候用户上传的图片方向不对,这样就需要旋转图片才能看到照片正确的方向,那么我们可以通过js旋转图片来实现。

完整示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>Image Editor</title>
    <style>
        img {
            max-width: 100%;
            max-height: 500px;
            display: block;
            margin: 0 auto;
        }
        button {
            margin-top: 10px;
            display: block;
        }
    </style>
    <script>
        function rotateImage() {
            var img = document.getElementById("myImage");
            var currentAngle = img.getAttribute("data-angle") || 0;
            var newAngle = parseInt(currentAngle) + 90;
            img.setAttribute("data-angle", newAngle);
            img.style.transform = "rotate(" + newAngle + "deg)";
        }
    </script>
</head>
<body>
<img id="myImage" src="https://www.itshiye.com/wp-content/uploads/2023/03/360se_picture.jpg">
<button onclick="rotateImage()">Rotate</button>
</body>
</html>

如果需要反向旋转,只需要把var newAngle = parseInt(currentAngle) + 90改成var newAngle = parseInt(currentAngle) – 90即可。

正文完
 
评论(没有评论)