js和canvas實現旋轉圖片
//點擊向左向右旋轉圖片
window.onload=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;
}
}
}
}
TAG:程序員小新人學習 |