js和canvas实现旋转图片

//点击向左向右旋转图片
window.οnlοad=function(){
var Img=document.getElementById(‘img’);
var inPut=document.getElementsByTagName(‘input’);
var num=0;
//加载图片
var newImg= new Image();
newImg.onload =function(){
draw(Img);
};
newImg.src=Img.src;

            function draw(obj){
                //创建一个画布
                var oc=document.createElement('canvas');
                var pc=oc.getContext('2d');
                oc.width =obj.width;
                oc.height = obj.height; 
                obj.parentNode.replaceChild(oc,obj);
                pc.drawImage(obj,0,0);
                inPut[1].onclick=function(){
                    num++;
                    if(num>3){
                        num=0;  
                    }
                    change();
                }
                inPut[0].onclick=function(){
                    num--;
                    if(num<0){
                        num=3;  
                    }
                    change();   
                }
                function change(){
                switch(num){
                    case 1:
                        oc.width = obj.height;
                        oc.height =obj.width;
                        pc.rotate(90*Math.PI/180);
                        pc.drawImage(obj,0,-obj.height);
                    break;
                    case 2:
                        oc.width =obj.width ;
                        oc.height =obj.height;
                        pc.rotate(180*Math.PI/180);
                        pc.drawImage(obj,-obj.width,-obj.height);
                    break;
                    case 3:
                        oc.width = obj.height;
                        oc.height =obj.width;
                        pc.rotate(270*Math.PI/180);
                        pc.drawImage(obj,-obj.width,0);
                    break;
                    case 0:
                        oc.width =obj.width ;
                        oc.height =obj.height;
                        pc.rotate(360*Math.PI/180);
                        pc.drawImage(obj,0,0);
                    break;
                    }   
            }
            }

        }

你可能感兴趣的:(js和canvas实现旋转图片)