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>

 

转载于:https://www.cnblogs.com/xiangguoguo/p/9557678.html

你可能感兴趣的:(JS_利用Canvas进行图片旋转)