js canvas 照片旋轉 demo
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/><!--以手機屏幕為標準,禁止放大縮小--> <meta name="format-detection" content="telephone=no"/><!--屏蔽IOS下自動轉換數字為手機鏈接--> <meta name="apple-mobile-web-app-capable" content="yes" /><!--IOS應用模式,自動隱藏默認的工具欄和菜單欄--> <meta name="browsermode" content="application"><!--UC應用模式--> <meta name="x5-page-mode" content="app"><!--騰訊X5瀏覽器應用模式--> <title>照片旋轉</title> </head> <body style="margin: 0;"> <input type="file" onchange="fileChangeEvent(this.files[0]);"/><br><br> <img style="width: 100%;" src="./1.jpg"/><br><br> <canvas style="display: none;"></canvas> <input type="button" value="90度"/><br><br> <input type="button" value="180度"/><br><br> <input type="button" value="270度"/><br><br> <input type="button" value="返回"/><br><br> </body> <script type="text/javascript"> var img = document.querySelector("img"); var canvas = document.querySelector("canvas"); var context = canvas.getContext('2d'); var imgHeight = 200; var imgWidth = 200; img.onload = function(){ imgHeight = img.height; imgWidth = img.width; } function fileChangeEvent(file){ var URL = window.URL || window.webkitURL; img.src = URL.createObjectURL(file); img.onload = function(){ imgHeight = img.height; imgWidth = img.width; } }function rotate90() { img.style.width = "initial"; // 防止 css 導致旋轉時的圖片寬高比拉伸而導致的模糊問題 canvas.width = imgHeight; canvas.height = imgWidth; context.translate(canvas.width * 0.5, canvas.height * 0.5); context.rotate(Math.PI * 0.5); context.translate(-canvas.height * 0.5, -canvas.width * 0.5); context.drawImage(img, 0, 0, imgWidth, imgHeight); img.src = canvas.toDataURL("image/png"); } function rotate180() { canvas.width = imgWidth; canvas.height = imgHeight; context.rotate(Math.PI); context.translate(-canvas.width, -canvas.height); context.drawImage(img, 0, 0, imgWidth, imgHeight); img.src = canvas.toDataURL("image/png"); } function rotate270() { img.style.width = "initial"; // 防止 css 導致旋轉時的圖片寬高比拉伸而導致的模糊問題 canvas.width = imgHeight; canvas.height = imgWidth; // 以中心點為基準旋轉,所有的旋轉只改變了 canvas 畫筆的坐標軸,對畫布沒有任何影響 context.translate(canvas.width * 0.5, canvas.height * 0.5); context.rotate(-Math.PI * 0.5); context.translate(-canvas.height * 0.5, -canvas.width * 0.5); context.drawImage(img, 0, 0, imgWidth, imgHeight); img.src = canvas.toDataURL("image/png"); } document.querySelectorAll("input[type='button']")[0].onclick = function(){ rotate90(); }; document.querySelectorAll("input[type='button']")[1].onclick = function(){ rotate180(); }; document.querySelectorAll("input[type='button']")[2].onclick = function(){ rotate270(); }; document.querySelectorAll("input[type='button']")[3].onclick = function(){ history.back(); }; </script>
</html></pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!