图片90度翻转
在canvas中插入图片需先加载图片(利用Image对象);加载完成后再执行操作drawImage(obj,x,y,w,h) 插入图片的坐标宽高等值
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="../css/public.css"/> <style type="text/css"> body{background: black;} canvas{background: #fff;display: block;margin: 20px auto;} button{width: 100px;height: 40px;line-height: 40px;text-align: center;} </style> <script type="text/javascript"> window.onload=function(){ var oBtn=document.getElementsByTagName('button'); var oImg=document.getElementById("img"); var oDiv=document.getElementsByTagName('div')[0]; var num=0; //在canvas中插入图片需要等图片加载完毕 var aImg=new Image(); aImg.src=oImg.src; aImg.onload=function(){ draw(oImg); } function draw(obj){ var oC=document.createElement('canvas'); var oG=oC.getContext("2d"); oC.width=obj.width; oC.height=obj.height; oDiv.replaceChild(oC,oImg); oG.drawImage(obj,0,0); oBtn[0].onclick=function(){ num--; if(num<0){ num=3; } toChange(); } oBtn[1].onclick=function(){ num++; toChange(); } function toChange(){ switch(num%4){ case 0: oC.width=obj.width; oC.height=obj.height; oG.rotate(0*Math.PI/180); oG.drawImage(obj,0,0); break; case 1: oC.width=obj.height; oC.height=obj.width; oG.rotate(90*Math.PI/180); oG.drawImage(obj,0,-obj.height); break; case 2: oC.width=obj.width; oC.height=obj.height; oG.rotate(180*Math.PI/180); oG.drawImage(obj,-obj.width,-obj.height); break; case 3: oC.width=obj.height; oC.height=obj.width; oG.rotate(270*Math.PI/180); oG.drawImage(obj,-obj.width,0); break; } } } } </script> </head> <body> <button id="right"><</button> <button id="left">></button> <div> <img src="../img/x.jpg" id="img"/> </div> </body> </html>