JS_利用Canvas进行图片旋转

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片旋转</title>
</head>
<body>
    <div>
        <input id="input" type="file" accept="image/*" onchange="show()"><br>
        <img id="img" src="" width="30%" alt="我是一张图片"><br>
        <button onclick="myRotate()">旋转</button>
    </div>
    <script>
        var base64="";
        function show(){
            var file=document.getElementById("input").files[0];
            var reader=new FileReader();
            reader.readAsDataURL(file);
            reader.onload=function(){
                base64=this.result;
                document.getElementById("img").src=base64;
            }
        }
        function myRotate(){
            debugger;
            var canvas=document.createElement("canvas");
            var context=canvas.getContext("2d");
            var img=new Image();
            img.src=base64;
            img.onload=function(){
                canvas.width=img.height;
                canvas.height=img.width;
                context.rotate(90*Math.PI/180);//顺时针旋转90°
                context.drawImage(img,0,-img.height,img.width,img.height);
                base64=canvas.toDataURL();
                document.getElementById("img").src=base64;
            }
        }
    </script>
</body>
</html>

 

posted @ 2018-08-29 23:31  喝醉的香锅锅  阅读(1094)  评论(1编辑  收藏  举报