test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片360度旋转</title> <style> input { font-size:18px; padding:5px 20px 5px 20px; font-weight:bold; color:white; background-color:#c5464a; cursor:pointer; border:none; outline:none; border-radius:7px 7px 7px 7px; } </style> <script type="text/javascript" src="test.js"></script> </head> <body> <input type="button" value="←"> <input type="button" value="→"> <div id="mydiv"> <img src="img3.jpg" id="img"> </div> </body> </html>
test.js
window.onload = function() { var inputval = document.getElementsByTagName(‘input‘); var imgval = document.getElementById(‘img‘); var yimg = new Image(); var iNow = 0; yimg.onload = function() { draw(imgval); } yimg.src = imgval.src; function draw(obj) { var c = document.createElement(‘canvas‘); var cxt = c.getContext(‘2d‘); c.width = obj.width; c.height = obj.height; obj.parentNode.replaceChild(c, obj); cxt.drawImage(obj, 0, 0); inputval[1].onclick = function() { if (iNow == 3) { iNow = 0; } else { iNow++; } toChange(); }; inputval[0].onclick = function() { if (iNow == 0) { iNow = 3; } else { iNow--; } toChange(); }; function toChange() { switch (iNow) { case 0: c.width = obj.width; c.height = obj.height; cxt.rotate(0 * Math.PI / 180); cxt.drawImage(obj, 0, 0); break; case 1: c.width = obj.height; c.height = obj.width; cxt.rotate(90 * Math.PI / 180); cxt.drawImage(obj, 0, -obj.height); break; case 2: c.width = obj.width; c.height = obj.height; cxt.rotate(180 * Math.PI / 180); cxt.drawImage(obj, -obj.width, -obj.height); break; case 3: c.width = obj.height; c.height = obj.width; cxt.rotate(270 * Math.PI / 180); cxt.drawImage(obj, -obj.width, 0); break; case 4: c.width = obj.width; c.height = obj.height; cxt.rotate(360 * Math.PI / 180); cxt.drawImage(obj, obj.width, obj.height); break; } } } }
图片:
效果:
2017-09-08 23:03:47
时间: 2024-11-10 22:04:20